本人学习vue.js中的vue-resource的过程中,按照文档写如下:
但是都会报错:Cannot read property 'get' of undefined (post、jsonp都会报错)
不知道为什么?
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="node_modules/vue-resource/dist/vue-resource.js"></script> <script src="node_modules/vue/dist/vue.js"></script> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> <body> <div id="app" class="container"> <h1>resource插件讲解</h1> <a href="javascript:;" class="btn btn-primary" v-on:click="get2">get请求</a> <a href="javascript:;" class="btn btn-primary" v-on:click="post">post请求</a> <a href="javascript:;" class="btn btn-primary" v-on:click="jsonp">jsonp请求</a> <div> <span>{{msg}}</span> </div> </div> </body> <script> new Vue({ el: "#app", data: { msg: "1" }, methods: { get2:function () { this.$http.get("package.json").then(res => { this.msg = res.data; }, error => { this.msg = error; }); }, post: function () { this.$http.post("package.json",{ userId: "456" }, { headers: { access_token: "qwer" }, emulateJSON: true }).then(function (res) { this.msg = res.data; }); }, jsonp: function () { this.$http.jsonp("package.json").then(res => { this.msg = res.data; }, error => { this.msg = error; }); } } }); </script> </html>
尤小右很早就建议不要用Vue-Resource了,请使用Axios代替。
1. 如上所说用 Axios 代替,或者用 fetch 也可以
2. 把这两行代码交换一下位置 <script src="node_modules/vue-resource/dist/vue-resource.js"></script> <script src="node_modules/vue/dist/vue.js"></script>