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
andcreated
, vue bindsthis
to the view-model instance for us, so we can usethis.followed
, but in the function insidethen
,this
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; }) },
完整代码: