Laravel5.4 Vuejs and Axios use hooks mounted cannot get property data resolution
Error problem:
In then
this inside of the assignment method this.followed = response.data.followed
will appear error, what reason? The original is then
inside cannot be instantiated with Vue, because it is this
this
not bound internally. Solve:self.followed = response.data.followed;或者使用 ES6
的 箭头函数arrow function
,箭头方法可以和父方法共享变量。
Here is my code:
Data properties:
data(){ return { followed : false, } },
Axios Request data:
// 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; }) },
Error problem:
In then
this inside the assignment method this.followed = response.data.followed
will appear error, what reason? On Google, the original is then
not used in the internal instantiation of Vue this
, because the internal is this
not bound.
Can look at the explanation of StackOverflow:
In option functions like data
created
and, Vue binds to the this
View-model instance for us, so we can use this.followed
, but in t He function inside then
, is not this
bound.
so-need to preserve the view-model like ( created
means the component's data structure is assembled, which are Enough here, would mounted
delay the operation more):
Workaround:
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; }) },
Or we can use ES6
the arrow function arrow function
, the arrow method can share the variable with the parent method:
created() { axios.post(‘/api/question/follower‘, { ‘question‘:this.question, ‘user‘:this.user }).then((response) => { this.followed = response.data.followed; }) },
Full code:
<Script>ExportDefault {The property value passed to the child component for the parent component, and the subcomponent receives the props:[using the props method' Question ',' User '],The mounted method is a hook that automatically calls mounted () after the Vue instantiation () {/** This old writing will be in the Laravel5.4 error this. $http. Post ('/api/question/follower ', {' question ': this.question, ' user ': This.user}). Then (response = {Console.log (response.data);}) */Axios.post ('/api/question/follower ', {' Question ':This.question,' User ':This.user}). Then (functionResponse) {Console.log (Response.data);this.followed = response.data.followed; })}, data () {return {followed: false,}}, computed:{text () {return this.followed? Span class= "hljs-string" > ' attention ': ' focus on the issue ';}, methods:{//attention action Follow () {Axios.post ( question ': this.question, ' user ': this.user}"). Then (function (response) {this.followed = response.data.followed;})} }}</SCRIPT>
Using Axios in Vuejs cannot get the solution for property data