【问题标题】:Vuex watch not triggereing on all state changesVuex watch 不会触发所有状态更改
【发布时间】:2020-04-06 01:49:18
【问题描述】:

我正在尝试观察 vue 组件中的 vuex 状态变化。 (我正在扩展一个更大的项目,并希望通过获取一些行信息并基于此渲染图像来对在一个组件中单击表行做出反应。)

状态更改有效(我可以在 vue 开发者工具中看到),但手表仅在初始加载/热重载时触发一次。我是 vue 和 vuex(以及 pug 和 ts)的新手,所以我想我缺少一些基本的东西。

我在这里找到了很多答案,说应该只看商店,显然还有更多。我尝试了几种变体(直接访问商店、导入商店模块和使用计算属性,但都没有工作,请参见下面的代码。我需要做什么才能使任何手表工作?

当我点击我创建的测试按钮时,所有信息也都出现了。

<template lang="pug">
    div
        p current image {{ imageUrl }}
        el-button(plain @click="onMyButtonClick") Button
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import { Getter, Action, Mutation, State } from 'vuex-class';
import { RecordModuleState } from '../store/modules/records/types';

@Component
export default class ImageViewer extends Vue {
    @State('records') private records!: RecordModuleState;

    onMyButtonClick (): void {
        console.log('Button clicked:', this.records.currentRow)
    }

    get imageUrl() {
        return this.records.currentRow // also tried this.$store.state.records.currentRow
    }

    @Watch('this.$store.state.records', { immediate:true, deep: true })
    onCurrentRowChanged(val: string, oldVal: string) {
        console.log('watch1', val)
    }

    @Watch('records', { immediate:true, deep: true })
    onCurrentRowChanged2(val: string, oldVal: string) {
        console.log('watch2', val)
    }

    @Watch('imageUrl', { immediate:true, deep: true })
    onCurrentRowChanged3(val: string, oldVal: string) {
        console.log('watch3', val)
    }

}  
</script>

【问题讨论】:

    标签: vue.js vuejs2 vuex


    【解决方案1】:

    您应该使用@Getter records,而不是使用@State('records') private records!: RecordModuleState;

    【讨论】:

    • 非常感谢您的浏览和建议。请您详细说明一下好吗?总体上使用状态是错误的,并且吸气剂是否提供了可以解决我的状态没有的问题的功能? IE。为什么一个工作而另一个失败?顺便说一句,只是交换两行没有用,我认为代码没有定义记录的吸气剂,我正在调查这个。谢谢!
    • 再次感谢您指出正确的方法。在实现了缺失的 getter 并查看了 mutation 之后,我现在可以通过任何一种方式让它工作,即观察计算属性的变化或通过观察 getter。感谢您指出我正确的方式! (仍然有兴趣知道为什么我应该使用吸气剂而不是访问商店以及是否有任何优点/缺点)。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 2013-07-21
    • 2020-02-17
    • 1970-01-01
    • 2016-03-07
    • 2013-03-29
    • 1970-01-01
    相关资源
    最近更新 更多