一、什么是vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化
二、vuex的五大核心
state: 数据
actions:可以包含异步操作
mutations: 唯一可以修改state数据的场所
getters: 类似于vue组件中的计算属性,对state数据进行计算(会被缓存)
modules:模块化管理store(仓库),每个模块拥有自己的 state、mutation、action、getter
三、vuex的执行流程
- 客户端操作事件,dispatch调用一个action
- 对应的action处理参数,比如接口/逻辑操作/传值/commit一个type类型
- mutation接收一个type类型触发对应的函数,修改state的值
- state更改后对应的view视图在render的作用下重新渲染
四、vuex的使用
4.1首先安装vue项目和vuex
4.2.新建store文件 创建一个Index.js 在index文件里面写下面代码:
在src路径下创建一个store文件,里面创建一个Index.js
import Vue from "vue"
import Vuex from "vuex"
//引入cart的vuex模块
import cart from "@/store/modules/cart.js"
Vue.use(Vuex)
export default new Vuex.Store({
//当做data
state:{
},
//相当于计算属性
getters:{
},
//同步一些方法
mutations:{
},
//存放异步的方法
actions:{
}
})
这里面的state就相当于data,getters相当于computed,mutations存放同步的方法,actions存放异步的方法。
4.3.在main.js中引入vuex
在main.js的入口文件引入并在new vue中初始化
注意引入的使用不加{}会报错,引入方式如下:
import { store } from “./store/index”
import Vue from 'vue'
import App from './App'
import store from './store' //引入vuex
Vue.prototype.$store = store //引入vuex
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
store, //引入vuex
...App
})
app.$mount()
4.4vuex
vuex中的数据源state,我们需要保存的数据就保存在这里。
将数据放在state中
4.5页面使用
在需要使用这些数据的文件中可以使用$store.state.xx调用数据
五、vuex持久化操作
问题:存储在vuex中的状态,刷新页面,会丢失。为了解决刷新页面数据丢失,才有了数据持久化。
最简单的做法就是利用插件 vuex-persistedState。
- 安装 cnpm install vuex-persistedState -S
-S 是–save的简写,意为:把插件安装到dependencies(生产环境依赖)中
-D是–save-dev的简写,意为:把插件安装到devDependencies(开发环境依赖)中
- 使用
import createPersistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
state,
mutations,
actions,
getters,
plugins: [createPersistedState({
storage: sessionStorage,
key: "token"
})]//会自动保存创建的状态。刷新还在
})
参数:
storage:存储方式。(sessionStorage,localStarage) key:定义本地存储中的key