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

VueJS: how to reference this.$store in component data property

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

我的 Veux 商店:

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

Vue.use(Vuex)

let store = new Vuex.Store({
        state: {
            user: {},
        },
    }
}
module.exports = store

我想在我的应用程序中使用商店数据并将其显示在模板中。但是,在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: {}

    }
};

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

根据 Vue documentation:

When defining a component, data must be declared as a function that returns the initial data object.

所以,改变:

data: {
    saving: false,
    user: this.$store.state.user
},

对此:

data: function () {
  return {
    saving: false,
    user: this.$store.state.user
  };
}

那么函数中的this就会引用$store.