Vuex是什么
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
也就是说创建一个所有组件都可以共享数据的文件,当一个组件去改变这个共享数据时,其余使用该共享数据的组件中的数据也会改变。
vuex中有一个state属性,state属性中存放着共享的数据
Vuex的配置
安装vuex
vue2项目安装vuex3,vue3安装vuex4
npm i vuex@3
配置vuex文件
在vue cli脚手架文件中,在src中创建vuex文件夹,在vuex文件夹中创建store.js文件
在store.js文件中
先引入vue和安装好的vuex
import Vue from 'vue'
import vuex from 'vuex'
将vuex进行全局挂载
Vue.use(vuex)
创键四个对象
const actions={}
const mutations={}
const state={}
const getters={}
创建store对象
const store = new Vuex.Store({
actions:actions,
mutations:mutations,
state:state,
getters:getter
})
导出store对象
export default store
导出store对象简写
export default new vuex.Store({actions,mutations,state,getters})
store.js文件中初始的配置代码
import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex)
const actions={}
const mutations={}
const state ={}
const getters = {}
export default new vuex.Store({actions,mutations,state,getters})
Vuex核心对象
actions
actions对象中都是action函数
通过store.dispath触发该函数
action函数是可以支持任意异步操作的
action函数有两个参数,context和value
context是上下文
value是从组件中传过来的数据
用法
context.commit('mutations中的回调函数',value)
mutations
mutations对象中都是mutation函数
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
mutation函数就是用来更新state对象中的数据
mutation函数也有两个参数,state和value
mutation函数必须是同步函数
这也就是为什么会有action函数,action函数是可以支持任意的异步操作
getters
getter可以理解为计算属性
相当于组件中的computed
state
共享的数据存放在state中
相当于组件中的data
Vuex在vue中的使用
完成一个案例,在输入框中选择输入用户还是vip,分别添加到名单中,并分别统计两名单人数
以下是具体代码实现
创建两个组件
user和vip
user组件
<template>
<div>
<input type="text" v-model="username">
<button @click="adduser">添加用户</button>
<ul>
<li v-for="user in $store.state.users" :key="user.id">
{{ user.name }}
</li>
</ul>
<h3>用户数量{{$store.state.users.length}}</h3>
<h3>vip数量{{$store.state.vips.length}}</h3>
</div>
</template>
<script>
export default {
name:'userNormal',
data(){
return {
username:''
}
},
methods:{
adduser(){
this.$store.dispatch('user',{id:Date.now(),name:this.username})
this.username=''
}
}
}
</script>
vip组件
<template>
<div>
<input type="text" v-model="vipname">
<button @click="addvip">添加vip</button>
<ul>
<li v-for="vip in $store.state.vips" :key="vip.id">
{{ vip.name }}
</li>
</ul>
<h3>用户数量{{$store.state.users.length}}</h3>
<h3>vip数量{{$store.state.vips.length}}</h3>
</div>
</template>
<script>
export default {
name:'vipUser',
data(){
return {
vipname:''
}
},
methods:{
addvip(){
this.$store.dispatch('vip',{id:Date.now(),name:this.vipname})
this.vipname=''
}
}
}
</script>