Javascript 使用非vuex状态管理在状态更改后更新模板
我正在制作一个应用程序,当你点击Javascript 使用非vuex状态管理在状态更改后更新模板,javascript,vue.js,state,Javascript,Vue.js,State,我正在制作一个应用程序,当你点击+按钮时,它会增加一个值 我正在跟踪调查 我已经设置了一个事件处理方法,它增加一个状态值。单击按钮时会触发此操作。它更新状态值,但模板不更新 为了证明这一点,我在我的increment函数中设置了控制台日志,以按预期触发并反映状态值。但是,DOM中的值永远不会更改: 我曾尝试将模板中的计数器值称为state.counterValue和store.state.counterValue,但我得到了控制台错误 我做错了什么 这是我的模板: <template&g
+
按钮时,它会增加一个值
我正在跟踪调查
我已经设置了一个事件处理方法,它增加一个状态值。单击按钮时会触发此操作。它更新状态值,但模板不更新
为了证明这一点,我在我的increment
函数中设置了控制台日志,以按预期触发并反映状态值。但是,DOM中的值永远不会更改:
我曾尝试将模板中的计数器值
称为state.counterValue
和store.state.counterValue
,但我得到了控制台错误
我做错了什么
这是我的模板:
<template>
<div>
<h1>{{store.state.counterValue}}</h1>
<button v-on:click="increment">+</button>
</div>
</template>
{{store.state.counterValue}
+
这是我的剧本:
<script>
const store = {
debug: true,
state: {
counterValue: 0
},
increment() {
console.log('updating counterValue...')
this.state.counterValue = this.state.counterValue + 1
console.log(this.state.counterValue)
}
}
export default {
data() {
return {
counterValue: store.state.counterValue
}
},
methods: {
increment: function() {
store.increment()
}
}
}
</script>
常数存储={
是的,
声明:{
计数器值:0
},
增量(){
console.log('正在更新计数器值…')
this.state.counterValue=this.state.counterValue+1
console.log(this.state.counterValue)
}
}
导出默认值{
数据(){
返回{
countvalue:store.state.countvalue
}
},
方法:{
增量:函数(){
store.increment()
}
}
}
code>{{store.state.counterValue}}的问题
从
mustache标记将替换为相应数据对象上的msg属性值
您的数据对象(即组件/vue实例)没有名为store
的属性。要访问常量存储
,您需要通过组件代理它:
data() {
return {
store: store
}
},
counterValue的问题:store.state.counterValue
这将This.counterValue
设置为等于store.state.counterValue
的初始值。但是没有代码保持它们的同步。因此,当store.state.counterValue
更改时,counterValue
将保持不变
解决方案 如上所述,通过组件进行代理
const-store
。例如:
const存储={
是的,
声明:{
计数器值:0
},
增量(){
console.log('正在更新计数器值…')
this.state.counterValue=this.state.counterValue+1
console.log(this.state.counterValue)
}
}
新Vue({
el:“#应用程序”,
数据(){
返回{
商店:商店
}
},
方法:{
增量:函数(){
this.store.increment();
}
}
})
{{store.state.counterValue}
+