使用非 vuex 状态管理在状态更改后更新模板

Update a template after state changes using non-vuex state management

我正在制作一个应用程序,它会在您单击 + 按钮时递增一个值。

我正在关注example from the documentation on Simple State Management

我已经设置了一个递增状态值的事件处理方法。单击按钮时会触发此事件。它会更新状态值,但模板不会更新。

为了证明这一点,我在我的 increment 函数中设置了控制台日志,该日志按预期触发并反映状态值。但是,DOM 中的值永远不会改变:

我曾尝试将模板中的 counterValue 称为 state.counterValuestore.state.counterValue,但我收到控制台错误。

我做错了什么?

这是我的模板:

<template>
<div>
  <h1>{{store.state.counterValue}}</h1>
  <button v-on:click="increment">+</button>
</div>
</template>

这是我的脚本:

<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>

{{store.state.counterValue}}

的问题

来自docs

The mustache tag will be replaced with the value of the msg property on the corresponding data object.

您的数据对象(即 component/vue-instance)没有名为 store 的 属性。要访问const store,需要通过组件代理:

data() {
  return {
    store: store
  }
},

counterValue: store.state.counterValue

的问题

这会将 this.counterValue 设置为 store.state.counterValue 的初始值。但是没有代码使它们保持同步。因此,当 store.state.counterValue 发生变化时,counterValue 将保持不变。


解决方案

通过组件代理 const store,如上所述。示例:

const store = {
  debug: true,
  state: {
    counterValue: 0
  },
  increment() {
    console.log('updating counterValue...')
    this.state.counterValue = this.state.counterValue + 1
    console.log(this.state.counterValue)
  }
}
new Vue({
 el: '#app',
  data() {
    return {
      store: store
    }
  },
  methods: {
    increment: function() {
      this.store.increment();
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.4/vue.js"></script>

<div id="app">
  <h1>{{store.state.counterValue}}</h1>
  <button v-on:click="increment">+</button>
</div>