【问题标题】:VueJS: how to reference this.$store in component data propertyVueJS:如何在组件数据属性中引用 this.$store
【发布时间】:2017-09-25 11:41:35
【问题描述】:

我想在我的应用程序和模板中使用我的 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: {}

    }
};

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

【问题讨论】:

  • 抱歉 this.$store 还没有定义所以我无法使用 this.$store.getters.getterMethod()
  • 数据需要是一个函数:vuejs.org/2016/02/06/common-gotchas
  • 是的,没错!!在文档中,它只提到将数据作为组件中的函数返回,但对于遇到此问题的任何其他人,也将数据作为应用程序的函数返回! PS谢谢添加这个作为答案,我会给你正确的答案

标签: javascript vue.js vue-component vuex


【解决方案1】:

根据Vue documentation

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

所以,改变:

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

到这里:

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

那么函数中的this就会有对$store的引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 2020-03-03
    • 1970-01-01
    • 2022-01-02
    • 2020-08-14
    • 1970-01-01
    • 2022-07-16
    相关资源
    最近更新 更多