Laravel5.4 在vuejs 中使用axios不能獲取屬性data的解決方法

Laravel5.4 vuejs和axios使用鉤子mounted不能獲取屬性data的解決方法vue

Here is my code:
數據屬性:ios

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

axios請求數據: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 沒有被綁定。
能夠看下 Stackoverflow 的解釋:api

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 then, this is not bound.babel

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):ide

解決方法:函數

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,箭頭方法能夠和父方法共享變量 :post

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

完整代碼:this

<script>
export default {
    // 爲父組件傳遞到子組件的屬性值,子組件使用props方法接收
    props:['question', 'user'],
    // mounted 方法爲鉤子,在Vue實例化後自動調用
    mounted() {
       /**  這種舊的寫法會在Laravel5.4中報錯
        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(function(response){
           // console.log(response.data);
           this.followed = response.data.followed;
       })
    },
    data(){
        return {
            followed : false,
        }
    },
    computed:{
        text(){
           return this.followed ? '已關注' : '關注該問題';
        }
    },
    methods:{
        // 關注動做
        follow(){
            axios.post('/api/question/follow', {
                'question':this.question,
                'user':this.user
            }).then(function(response){
                this.followed = response.data.followed;
            })
        }
    }
}
</script>

參看文章:
Stackoverflow:Axios can't set datacode

相關文章
相關標籤/搜索