1

下面的简单代码让我很头疼,因为 some-component 和 root 实例都将错误记录到控制台而不是从 vuex 对象绑定。我可能在这里缺少什么?

var state = {
	counter: 0
};
var mutations = {};
var store = new Vuex.Store({state, mutations});

var someComponent = Vue.extend({
  template: '<div>{{counter}}</div>',
  //data: function(){return {counter: 0}},
  vuex: {
    getters: {
      counter: getCounter
    }
  }
});

new Vue({
  el: '#app',
  components: {
  	'some-component': someComponent
  },
  store: store,
  vuex: {
  	getters: {
  		counter: getCounter
  	}
  }
});


function getCounter(state) {
  return state.counter;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>vue-bug</title>
  </head>
  <body>
    <div id="app">
    	<span>{{counter}}</span>
    	<some-component></some-component>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.0-rc.1/vue.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.0.0-rc.1/vuex.js"></script>
  </body>
</html>

在我的代码中,我调用了 Vue.use(Vuex),但在这个小提琴中我不必(它说 Vuex 已经注册)。另外,请注意,如果您取消注释数据行,组件将正确呈现。

任何帮助是极大的赞赏。

4

1 回答 1

3

如果你使用的是 Vue/Vuex 2.0,你应该看看这个链接。在 vuex 2.0 中,您无需vuex在组件内创建属性来设置 getter 和操作。相反,在您的store.js文件中定义一个 getters 对象,您将从状态中获取道具,然后将其注入商店,如下所示:

const state = {
    counter: 0
}
const getters = {
    getCounter: state.counter
}

const actions = {}
const mutations = {}

export default new Vuex.Store({
    state,
    getters,
    actions,
    mutations,   
 })

在您的组件中,您可以使用计算属性定义 getter,如下所示:

import { mapGetter, mapActions } from 'vuex'

export default {
    template: '#some-template',
    computed: {
        yourFirstComputed() {},
        anotherOfYourComputed() {},
        ...mapGetters({
            getCounter: 'getCounter'
        })
    },
    methods: {
        yourMethod(){},
        ...mapActions({
             anyOfYourActions: 'anyOfYourActions'
        })
    }
}

然后你可以像使用普通计算一样调用这些道具。我再说一遍,这适用于 vuex 2,我认为您在阅读问题的评论后正在使用它。

我希望它有帮助!

于 2016-09-14T12:44:35.093 回答