一.state
介绍:里面是一个个数据
state: { name:"vuex" },
利用计算属性获取:
computed:{
name(){
return this.$store.state.name
},
直接在页面使用
<h1> {{name}} </h1>
二.getters
介绍:由计算属性派生的数据
getters: {
info(state){
return `我是${state.name},你对我做了什么`
}
},
获取与使用方式(与state用法一致)
获取
computed:{
info(){
return this.$store.getters.info
}
},
使用
<div>{{info}}</div>
三.mutations
介绍:改变数据,里面不能写异步代码
mutations: {
m_name(state,value){
state.name=value
}
},
<button @click="changeName">改变name</button>
methods:{
changeName(){
this.$store.commit('m_name','(记得开启严格模式)vux改变咯')
}
}
四.actions
介绍:通知mutations改变数据,里面写异步代码
dispatch 分发给actions
语法:this.$store.dispatch(actions异步名称,需要的数据)
created(){
this.$store.dispatch('a_seller',{id:1})
},
commit 提交给 mutations
语法:
async actions异步名称(sss,需要的数据){
// 请求数据
// 提交给 mutations,
sss.commit(mutations,数据)
}
actions: {
async a_seller({commit},value){
let res =await axios({
url:'xxxxx',
data:value
})
// 提交给 mutations,
commit('m_seller',res.data.data)
}
},
五.各类辅助函数
(1)引入
import {函数名} from 'vuex'
(2)使用
computed:{
// 辅助函数的作用
// 01 简写代码
// ...mapState([name]),
// 02 支持重命名 name=>reName
...mapState(,{
reName:'name'
}),
...mapGetters(['info']),
},
mapState,mapGetters, mapMutations, mapActions同理
六.modules
介绍:由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。
为了解决以上问题,Vuex 允许我们将 store 分割成模块(module) 。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:
(1)引入模块
import 模块名 from ‘路径’
(2)modules开启namespaced
原因:子模块a与子模块b 的命名(可能)冲突
(3)注册模块
modules: {
模块名:模块名
}
子模块的使用
需要添加 子模块名 如:seller
computed:{
// 辅助函数的作用
// 01 简写代码
// ...mapState('seller',['name']),
// 02 支持重命名 name=>reName
...mapState('seller',{
reName:'name'
}),
...mapGetters('seller',['info']),
},
mapGetters, mapMutations, mapActions同理