博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在vuejs 中使用axios不能获取属性data的解决方法
阅读量:4497 次
发布时间:2019-06-08

本文共 1622 字,大约阅读时间需要 5 分钟。

Laravel5.4 vuejs和axios使用钩子mounted不能获取属性data的解决方法

//出错问题:

then 这个里边的赋值方法this.followed = response.data.followed会出现报错,什么原因呢?原来是在 then的内部不能使用Vue的实例化的this, 因为在内部 this 没有被绑定。解决:self.followed = response.data.followed;或者使用 ES6 的 arrow function,箭头方法可以和父方法共享变量。

Here is my code:

数据属性:

data(){        return {            followed : false, } },

axios请求数据:

// mounted 方法为钩子,在Vue实例化后自动调用    mounted() {       axios.post('/api/question/follower', {           'question':this.question,           'user':this.user }).then(function(response){ // console.log(response.data); this.followed = response.data.followed; }) },

出错问题:

then 这个里边的赋值方法this.followed = response.data.followed会出现报错,什么原因呢?在Google上查了下,原来是在 then的内部不能使用Vue的实例化的this, 因为在内部 this 没有被绑定。
可以看下  的解释:

In option functions like data and created, vue binds this to the view-model instance for us, so we can use this.followed, but in the function inside thenthis is not bound.

So you need to preserve the view-model like (created means the component's data structure is assembled, which is enough here, mounted will delay the operation more):

解决方法:

created() {       var self = this;       axios.post('/api/question/follower', {           'question':this.question, 'user':this.user }).then(function(response){ // console.log(response.data); self.followed = response.data.followed; }) },

或者我们可以使用 ES6 的 arrow function,箭头方法可以和父方法共享变量 :

created() {       axios.post('/api/question/follower', {           'question':this.question,           'user':this.user }).then((response) => { this.followed = response.data.followed; }) },

完整代码:

 

转载于:https://www.cnblogs.com/blogNYGJ/p/8547086.html

你可能感兴趣的文章
sql查询最大的见多了,查询第二的呢???
查看>>
Heimstaettenwegherb,村里最盛大的节日
查看>>
iOS 设置控件大小根据文本的大小
查看>>
MapReduce Design Patterns(7、输入输出模式)(十四)
查看>>
JS函数式编程【译】3.2 开发和生产环境
查看>>
火柴棍等式
查看>>
EasyUI中DataGrid构建复合表头
查看>>
[转]How to compile GDB for iOS!
查看>>
redis windows安装
查看>>
python有序字典OrderedDict()
查看>>
sql 检索字符串
查看>>
常用正则表达式
查看>>
HDU 4280 最大流Dinic算法优化
查看>>
八大排序算法
查看>>
why dropout work?
查看>>
小白成长记-----python实现注册的小程序
查看>>
Codeforces Round #151 (Div. 2)总结
查看>>
cin问题 分类: c++ 2014-08-02 2...
查看>>
PHP 中文字符串相关
查看>>
开始搭建 myBatis.net + Spring.net + asp.net mvc 3 + easyUI 开发平台
查看>>