vuex是一个专门为vue.js设计的集中式状态管理架构。相当于一个数据仓库,管理状态。
状态怎么理解呢?可以理解为在data中的属性需要共享给其他vue组件使用的部分,就叫做状态。简单的说就是data中需要共用的属性。eg:我们有几个页面要显示用户名称和用户等级,或者显示用户的地理位置。如果我们不把这些属性设置为状态,那每个页面遇到后,都会到服务器进行查找计算,返回后再显示。在中大型项目中会有很多共用的数据,所以我们用到vuex。
cnpm install vuex --save
需要注意的是,一定要加上--save,因为这个包我们需要在开发环境中使用。
这样就安装成功了。
store.js
文件(新建数据仓库),文件中引入我们的vue和vuex。import Vue from ‘vue‘;
import Vuex from ‘vuex‘;
Vue.use(Vuex);
通过这三步的操作,vuex就算引用成功。
我们这个小案例先声明一个state的count状态,在页面中使用显示这个count,然后可以利用按钮进行加减。不过我们这次要用的是vuex来进行制作,并实现数据的共享。
store.js
文件里增加一个常量对象。store.js
文件就是我们在引入vuex时的那个文件。const state = {
count:1
}
export default new Vuex.Store({
state //这里的状态先简单理解一下
})
Count.vue
。在模板中我们引入我们刚建的store.js
文件,并在模板中用$store.state.count
输出count 的值。<template>
<div>
<h2>{{msg}}</h2>
<hr>
<h3>{{$store.state.count}}</h3>
</div>
</template>
<script>
import store from ‘@/vuex/store‘
export default {
data(){
return{
msg:‘Hello Vuex‘
}
},
store
}
</script>
import Vue from ‘vue‘
import Router from ‘vue-router‘
import HelloWorld from ‘@/components/HelloWorld‘
import Count from ‘@/component/Count‘
Vue.use(Router)
export default new Router({
routes: [
{
path: ‘/‘,
name: ‘HelloWorld‘,
component: HelloWorld
},{
path:‘/count‘,
component:Count
}
]
})
先看一下:
那我们需要做两个按钮,实现加减:
在Count.vue的template中加入:
<p>
<button @click="">+</button>
<button @click="">-</button>
</p>
现在要在store.js仓库中写方法,必须通过mutations,这里为固定写法:
const mutations={
add(state){
state.count++;
},
reduce(state){
state.count--;
}
}
在下方的export default中也要加上我们mutations:
export default new Vuex.Store({
state,
mutations
})
<p>
<button @click="$store.commit(‘add‘)">+</button>
<button @click="$store.commit(‘reduce‘)">-</button>
</p>
这样进行预览就可以实现对vuex中的count进行加减了。
原文:https://www.cnblogs.com/Elva3zora/p/12714499.html