在Vue中,我们可以使用vuex进行状态管理。vuex是Vue的官方状态管理库,提供了集中式存储和管理应用的各种状态,以便于不同组件之间的通信和数据共享。代码讲解
<div id="app"> <p>计数器:{{ count }}</p> <button @click="increment">增加</button></div><script src="https://unpkg.com/vue/dist/vue.js"></script><script src="https://unpkg.com/vuex"></script><script>const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++ } }})new Vue({ el: '#app', store, computed: { count() { return this.$store.state.count } }, methods: { increment() { this.$store.commit('increment') } }})</script>
在上述示例中,我们创建了一个简单的计数器,并使用vuex进行状态管理。我们通过this.s t o r e . s t a t e 来获取状态,通过 ‘ t h i s . store.state来获取状态,通过`this.store.state来获取状态,通过‘this.store.commit`来提交变更。