【问题标题】:How to watch two more stores in Vue.js and Vuex?如何在 Vue.js 和 Vuex 中观看另外两个商店?
【发布时间】:2018-01-10 21:15:58
【问题描述】:

我正在使用 Vue.js 和 Vuex。 我想watchstore 的值(我将在本文的最后分享我的示例代码)。 但是我遇到了错误“错误:[vuex] store.watch 只接受一个函数。”

在这个网站上,我发现了如何使用“单一”商店。 https://codepen.io/CodinCat/pen/PpNvYr

但是,就我而言,我想使用“两个”商店。 你有什么办法解决这个问题吗?

●index.js

'use strict';
import Vue from 'vue';
import Vuex from 'vuex';

import {test1Store} from './modules/test1.js';
import {test2Store} from './modules/test2.js';

Vue.use(Vuex);
export const store = new Vuex.Store({
    modules: {
        test1: test1Store,
        test2: tes21Store,
    }
});

●test1.js

'use strict';
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
export const checkerStore = {
    namespaced: true,
    state: {
        count: 1
    },

    getters: {
        getCount(state){
            return state.count;
        }
    }
};
export default {test1};

●test.vue

<template>
    {{ $store.state.couunt }}
</template>

<script>
    import {store} from './store/index.js';
    export default {
        data: function () {
            return {

            }
        },
        store: store,
        methods: {

        },
        mounted() {
            setInterval(() => { this.$store.state.count++ }, 1000);
            this.$store.watch(this.$store.getters['test1/getCount'], n => {
                console.log('watched: ', n)
                })
            }
        }
    }
</script>

【问题讨论】:

标签: vuejs2 vuex


【解决方案1】:

您收到该错误是因为在您的示例代码中,您传递给watch 的第一个参数,正如错误所暗示的,不是function

该参数实际上是在 Vue 底层使用原生 JavaScript 调用 Object.defineProperty 实现的,所以像你一样执行 store.getters['test1/getCount'] 的结果实际上是一个 number

我认为不建议在像您这样的场景中使用watch,但如果您坚持,您可以通过提供替代参数形式来访问count,例如:

this.$store.watch((state, getters) => getters['test1/getCount'], n => { ... })

【讨论】:

  • 非常感谢!!我可以解决我的问题并使用您的建议代码。如果可以的话,我想知道你为什么说I don't think it's recommended to use watch in a scenario like yours。谢谢,
  • @ketancho,没问题,我很高兴我的回答有帮助。至于我的建议,我不确定您在 watch 回调中到底在做什么,但如果您只是通过使用新值来计算其他内容来响应状态更改,请使用 computed property 是一种更清洁的方法来实现这一点。如果你错过了,official documentation 有很好的例子。
  • 非常感谢!!我尝试详细阅读官方文档,并认为在我的情况下哪种方法更好。谢谢!!!!
猜你喜欢
  • 1970-01-01
  • 2022-01-03
  • 2020-05-09
  • 2019-04-28
  • 1970-01-01
  • 1970-01-01
  • 2018-09-08
  • 1970-01-01
  • 2021-06-14
相关资源
最近更新 更多