1.什么是vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化
2.vuex能做什么
存储组件公共数据
3.vuex的核心
vuex共有六大核心
state:存储数据,存放vuex中的数据。
mutations:存储方法 用来直接操作state中的数据。我们现在mutations中定义一个方法,设置两个参数分别是state和自定义参数,然后在页面中使用this.$store.commit('定义的方法名',参数)。
export default new Vuex.Store({
state: {
token:'',
username:''
},
mutations: {
addtoken(state,data){
state.token = data.token
state.username = data.username
}
},
actions: {
},
modules: {
}
})
vue组件中通过事件来触发。
<script>
methods:{
add(){
var obj = {
token:res.data.data.remember_token,
username:res.data.data.nickname
}
this.$store.commit('addtoken',obj)
}
}
</script>
actions:存储方法 调用mutations中的方法 里面的方法返回的是promise对象可以实现异步操作
export default new Vuex.Store({
//存放数据
state: {
count: 5,
},
//2.接受dispatch传递过来的方法和参数
actions: {
getParamSync (context,val) {
//处理异步操作
setTimeout(()=>{
//3.通过commit提交一个名为getParam的mutation
//action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation
context.commit('increment',val)
},3000)
}
}
})
vue组件中通过事件触发action
methods: {
getVal() {
//1.通过dispatch将方法getParamSync和多个参数{name,age,sex}传递给actions
this.$store.dispatch('getParamSync',1)
}
}
getters:对state中的数据做逻辑计算 类似于computed。
getters 接受 state 作为其第一个参数
const store = new Vuex.Store({
//state存储应用层的状态
state:{
count:5 //总数:5
},
getters:{
newCount:state => state.count * 3
}
});
modules:模块存储。
怎么使用modules呢?
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB})
使用
// computed属性,从store 中获取状态state,不要忘记login命名空间。
computed: {
useName: function() {
//return store.state.login.useName
return this.$store.state.moduleA.useName
}
},
methods:{
changeName(){
this.$store.dispatch("changeName",'jason');
}
}
}
plugins:插件(持久化存储)。
4.vuex的运行原理
在组件中通过dispatch来调用actions中的方法,在actions中通过commit来调用mutations中的方法,在mutaions中的方法中可以直接操作state中的数据,只要state中的数据发生改变,就会立即响应到所有的组件上
5.vuex的使用
1.基本使用 在vue的原型上有一个$store对象可以调用vuex的任何东西
-
state this.$store.state.**
-
mutations this.$store.commit("方法名",参数) 参数只能传一个
-
actions this.$store.dispatch("方法名",参数)
-
getters this.$store.getters.**
-
module this.$store.模块名.state
2.使用映射函数
将vuex的中的成员映射到组件中然后使用
mapState mapMutations mapGetters mapActions
步骤:
-
在组件中导入需要的函数
import {mapState,mapGetters **} from "vuex"
-
映射函数在组件中对应位置
-
mapState --computed
-
mapGetters --computed
-
mapMutations--methods
-
mapActions--methods
-
-
语法
computed:{ ...mapState(['student']) }
6.vuex的持久化
就是将vuex的数据存储在本地(localStorage sessionStorage)
可以选择手动的去写,但是比较麻烦所以选择 插件
-
下载
cnpm install vuex-persistedstate --save
-
配置 store->index.js
import persistedState from 'vuex-persistedstate'
默认的使用localStorage plugins: [persistedState()] 还可以配置成sessionStorage plugins: [persistedState({storage: window.sessionStorage})]
(只是本人的一点小见解,欢迎补充,如有不当的地方还望谅解!)