【发布时间】: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>
【问题讨论】: