VueJS:如何在组件数据属性中引用this。$ store

joh*_*hnm 5 javascript vue.js vue-component vuex

我想在我的应用程序和模板中使用Vuex存储数据。

我的Veux商店:

var Vue = require('vue');
var Vuex = require('vuex');

Vue.use(Vuex)

let store = new Vuex.Store({
        state: {
            user: {},
        },
    }
}
module.exports = store
Run Code Online (Sandbox Code Playgroud)

我想在我的应用程序中使用存储数据并将其显示在模板中。但是,在data属性中设置数据时this.$storeundefined。但是,我可以在beforeRender函数中访问它:

var Vue = require('vue'),
store = require('../../link/to/my/store');

module.exports = {
    el: '#selector',

    store,

    components: {},

    data: {
        saving: false,
        user: this.$store.state.user // this.state is not available here
    },

    created: function(){},
    beforeCreate: function() {

        console.log(this.$state.state) // this.$state is available here

        // i get my data in the form of a json string from the dom
        // and update the global store with the data
        let user = document.querySelector('#user-data')
        if (user) this.$store.dispatch('updateUser', JSON.parse(user.innerHTML))

    },

    methods: {}

    }
};
Run Code Online (Sandbox Code Playgroud)

我也尝试过计算属性,但无济于事。

tha*_*ksd 5

根据Vue文档

定义组件时,必须将数据声明为返回初始数据对象的函数。

因此,更改:

data: {
    saving: false,
    user: this.$store.state.user
},
Run Code Online (Sandbox Code Playgroud)

对此:

data: function () {
  return {
    saving: false,
    user: this.$store.state.user
  };
}
Run Code Online (Sandbox Code Playgroud)

然后this,函数中的将引用$store