vuex是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
按照自己理解来说就是公共数据管理模块。如果应用中数据量比较大的可以应用,不是很大的建议用缓存即可。
vuex的模块
- 存放数据:state
- 更新数据:mutaions(唯一方式)
- 动作:actions(异步api操作)
- 计算:getters(从现有的state计算出新的数据)
- 模块:modules
state:{ gTitle:{ text:"你好Vuex", color:"#000", fontSize:"24px", background:"#f70" },
初始化
store文件下的index.js
import Vuex from 'vuex';
import Vue from 'vue';
Vue.use(Vuex);
export default new Vuex.Store({
state:{},
mutations:{},
actions:{},
getters:{},
modules:{},
})
在main.js导入定义全局$store
import store from './store/index.js'
Vue.prototype.$store = store;
- pages,json 配置页面
state定义数据
- 在页面中使用
- $store.state.gTitle.text
- 修改只能通过mutations
- 组件中简写
- import {mapState} from 'vuex'
- computed:{
...mapState(["gTitle"])