首页 > 解决方案 > 如何使用函数在 data() 上的变量内设置值?

问题描述

我正在 Laravel 应用程序中创建一个 Vue.js 组件。

在我通过 axios 请求捕获响应后,我无法将值放入方法 data() 的变量中

这是代码:

应用程序.js

require('./bootstrap')

window.Vue = require('vue')

Vue.component('card', require('./components/card.vue'))


let app = new Vue({
    el: '#app'
})

卡片.vue

<script>
module.exports  = {
    props: [
        'name'
    ],
    data: function() {
        return {
            projects: [],
        }
    },
    mounted() {
        this.getProjects() // NOT WORK?
    },
    methods: {
        getProjects: function() {
            axios.get('/api/v1/getProjects').then(function (response) {

                console.log(response.data)
                this.projects = response.data // NOT WORK

            }).catch(function (error) {

                console.log(error)

            }).then(function () {

            })
        },
    }
}
</script>

标签: vue.jsvue-component

解决方案


尝试添加.bind(this)或替换function=>

getProjects: function() {
        axios.get('/api/v1/getProjects').then((response) => {

            console.log(response.data)
            this.projects = response.data // NOT WORK

        }).catch((error) => {

            console.log(error)

        }).then(function () {

        })
    },

推荐阅读