使用Vuex实现最简易的计数功能
在Vue中,组件可以分为数据和视图两个部分,数据更新时试图也会随之更新,在视图中也可以绑定一些时间用于触发methods里指定的方法,从而改变数据、更新视图等操作,但是传统的Vue只能在本组件控制其他的组件就没有办法独去或修改,而Vuex就弥补了这个缺点,可以做到跨组件共享数据,话不多说直接操作。
1、Vuex是一个插件首先需要安装Vuex(所有npm的地方都可以换成cnpm将不再叙述)
npm install vuex --save
然后在Vue项目下的src文件夹中创建store文件夹意思意思为数据库,并在store下新建index.js 如图所示:

内部代码如下:
import Vue from 'vue'; import Vuex from 'vuex';//引入Vuex插件 Vue.use(Vuex);//调用Vue.use()方法使用 export default new Vuex.Store({ //state存放所有的共享数据 state:{ count:0 }, //状态的变化 mutations:{ increment(){ this.state.count++; }, decrement(){ this.state.count--; } } });
接着需要在main.js中引入store数据源,并在Vue实例中使用,main.js的代码如下:
import Vue from 'vue' import home from './components/counter.vue' import router from './router' import store from './store/index'//引入刚才写的index.js文件 Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, components: { home }, template: '<home/>' });
main.js配置也结束了,接下来就是如何在实例当中使用了,在index.js中已经写了increment方法和decrement方法,接下来在实例中去使用,代码如下:
<template>
<div class="page">
<p>{{count}}</p>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
</div>
</template>
<script>
export default {
data() {
return {}
},
computed:{
count(){
return this.$store.state.count;
}
},
methods: {
increment(){
//改变store中的状态唯一途径就是显式的提交
this.$store.commit("increment");
},
decrement(){
this.$store.commit("decrement");
}
},
}
</script>

浙公网安备 33010602011771号