vuex是专门用来管理vue.js应用程序中状态的一个插件。他的作用是将应用中的所有状态都放在一起,集中式来管理。
store
vuex 中最关键的是store对象,这是vuex的核心。可以说,vuex这个插件其实就是一个store对象,每个vue应用仅且仅有一个store对象
创建storeconst store = new Vuex.Store({...});```
五大核心
- 1.state – 存放状态
state上存放的,说的简单一些就是变量,也就是所谓的状态。没有使用 state 的时候,我们都是直接在 data
中进行初始化的,但是有了 state 之后,我们就把 data 上的数据转移到 state
上去了。另外有些状态是组件私有的状态,称为组件的局部状态,我们不需要把这部分状态放在store中去。
this.$store.state.数据名 //进行读取
- 2.getters – state的计算属性
this.$store.getter.数据名 //进行读取
- 3.mutations – 更改状态的逻辑,同步操作
this.$store.commit.('事件名',参数) //进行读取
- 4.actions – 提交mutation,异步操作
this.$store.dispatch.('事件名',参数) //进行读取
- 5.mudules – 将store模块化
如何使用
store—>index.js
import vue from 'vue'
import Vuex from 'vuex'
Vue.use(vuex);
const state= ()=>{ token:''}
const actions = {
set_token({commit},val){
commit("to_token",val)
}
}
const mutations = {
to_token(state,val){
state.token=val;
}
}
const getters = {}
let store = new Vuex.store({
state,
actions,
mutations,
getters
})
module.export=store;
home.vue
<template>
<div>
{{$store.state.token}}
</div>
</template>
<script>
export default={
name: 'Home',
data() {
return {
tel: '',
}
},
created(){
//调用acionts中的方法
this.$store.dispatch('set_token',12345);
//调用mutations中的方法
this.$store.commit('to_token',123456)
}
}
<script>
高级用法-之 数据持久化
问题:存储在vuex中的状态,刷新页面,会丢失。
为了解决刷新页面数据丢失,才有了数据持久化。
最简单的做法就是利用插件vuex-persistedState
。
1. 安装
cnpm install vuex-persistedState -S
-S 是
--save
的简写,意为:把插件安装到dependencies
(生产环境依赖)中
-D是--save-dev
的简写,意为:把插件安装到devDependencies
(开发环境依赖)中
2. 使用
import createPersistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
state,
mutations,
actions,
getters,
plugins: [createPersistedState({
storage: sessionStorage,
key: "token"
})]//会自动保存创建的状态。刷新还在
})
3.参数
storage:存储方式。(sessionStorage,localStarage) key:定义本地存储中的key
高级语法-值 模块化管理数据 (modules)
1. 什么时候需要用到模块管理vuex数据。
项目庞大,数据信息量特别大的时候,我们可以考虑分模块形式管理数据,比如user模块管理用户信息数据,cart模块管理购物车数据,shop模块管理商品信息数据。
import vue from 'vue'
import Vuex from 'vuex'
Vue.use(vuex);
const state= ()=>{ token:''}
const actions = {
set_token({commit},val){
commit("to_token",val)
}
}
const mutations = {
to_token(state,val){
state.token=val;
}
}
const getters = {}
//user模块
let user = {
namespaced: true, //一定要开始命名空间。
state: { userid: 1234 },
actions: {
},
mutations: {
SET_USERID(state, val) {
state.userid = val;
}
},
getters: {
}
}
//购物车数据的模块
let cart = {
namespaced: true,
state: { userid: 567 },
actions: {
},
mutations: {
},
getters: {
}
}
const store = new Vuex.Store({
state,
mutations,
actions,
getters,
modules: {
user,
cart
},
plugins: [createPersistedState({
storage: sessionStorage,
key: "token"
})]//会自动保存创建的状态。刷新还在
})
export default store
home.vue如何使用
获取user模块的`userid`
this.$store.state.user.userid
this.$store.commit("SET_USERID",12345)
高级用法-之 辅助函数(语法糖)
1. 有那几个辅助函数(4大金刚)
mapState,mapActions,mapMutations,mapGetters
2. 辅助函数可以把vuex中的数据和方法映射到vue组件中。达到简化操作的目的
3. 如何使用