状态管理
大约 2 分钟
Vuex
Vuex是一个专为Vue.js应用程序开发的状态管理模式 每一个Vuex应用的核心就是store(仓库),store基本上就是一个容器,它包含着你的应用中大部分的状态
npm install vuex -S
import Vuex from 'vuex'
Vue.use(Vuex)
var store = new Vuex.Store({
//state类似于vue实例中的data属性,用来存储公共数据
state:{username:'zs'} ,
//mutation类似于vue实例中的methods,用来定义修改数据的函数
mutations:{
//mutations中定义的函数第一个参数是固定的,就是store中的state,第二个参数是外界在调用该函数时传递的参数
changeUserName(state,value){
state.username = value
}h
},
//getters类似于vue实例中的计算属性、过滤器,可以定义一些依赖其他数据变化的数据
getters:{
fixName(state){
return 'H=ello! ' + state.username;
}
},
//actions和mutations都是定义对数据进行操作的方法,mutations中都是同步方法,actions中定义异步方法,action提交的是mutation,而不是直接变更状态,所以需要修改状态还是需要使用mutations中定义的方法。从网络请求回来的数据需要保存到store,发送网络请求的方法可以定义到actions中,actions主要用于处理异步方法
actions:{
asyncchange(context,arg){
setTimeout(()=>{context.commit('change',arg)},3000)
}
}
});
new Vue({ .. ,store}) //在Vue实例中挂载
使用 state
{
{
$store.state.username
}
}
使用 mutations
this.$store.commit('changeUserName', this.name)
参数1需要调用的函数名称,参数2需要传递给该函数的数据
使用 getters
{
{
$store.getters.fixName
}
}
使用 actions
this.$store.dispatch('action', parsms)
给组件绑定原生事件,需要加.native修饰符
插槽
<template slot-scope="slotProps">
<!-- 为待办项自定义一个模板,-->
<!-- 通过 `slotProps` 定制每个待办项。-->
<span v-if="slotProps.todo.isComplete">✓</span>
{{ slotProps.todo.text }}
</template>
在组件中
<template>
<div :class="isSeniors?'search-main is-show':'search-main'">
<el-row type="flex" class="fix-select">
<el-col :span="12">
<slot name="btnBox"></slot>
</el-col>
<el-col :span="12" align="right">
<slot name="simpleSearch"></slot>
<el-form-item v-if="isSenior">
<el-button type="text" size="mini" @click="search">搜索</el-button>
</el-form-item>
</el-col>
</div>
</template>
在使用了该components中
<search-panel @onSearch="onSearch">
<template slot="btnBox">
<el-button type="primary" size="mini" class="btn btn-primary">
新 建
<i class="el-icon-arrow-down el-icon--right"></i>
</el-button>
</template>
<template slot="simpleSearch">
<el-input size="mini" suffix-icon="el-icon-search"></el-input>
</template>
</search-panel>
辅助函数
mapState和mapGetters可以将store中的state和getters中定义的数据映射到组件中计算属性里面,this.$store.getters.getGoodsCount写法更改getGoodsCountmapMutations,mapActions可以将store中的state和getters中定义的数据映射到组件中的methods里面,this.$store.commit('foo',data)写法this.foo(data);
import {mapState,mapMutations,mapGetters,mapActions} from 'vuex'
export default {
computed:{
...mapState([
'car'
]),
...mapGetters([
'getGoodsCount',
'getGoodsSelected'
'getGoodsCountAndAmount'
])
// ...mapGetters({
// count:'getGoodsCount'
// })
...mapMutations({
'updateGoodsSelected':'updateGoodsSelected',
'remove':'removeFormCar'
})
}
}
