安装
-
HTML 中使用 script 标签引入
<script src="vue.js"></script> <script src="vuex.js"></script> -
vue项目中使用 npm 下载安装(需要安装 Node 环境)
// 下载 npm install vuex --save // 安装 import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex)
Vue 项目中 vuex 的使用
-
store.js
import Vuex from 'vuex' Vue.use(Vuex) export default Vue.prototype.$store = new Vuex.Store({//声明了全局变量 state:{}, getters:{}, mutations:{}, action:{} }) -
main.js
import store from './store'; new Vue({ el: '#app', store, components: { App }, template: '<App/>' })
默认的五种基本的对象
-
state:存储状态(变量),组件中使用this.$store.state.count
state: { count: 0 } -
getters:对数据获取之前的再次编译,即state的计算属性,组件中使用 $sotre.getters.fun()
getters: { getterCount(state, n = 0) { return (state.count += n) } } -
mutations:修改状态,并且是同步的。组件中使用$store.commit('',params)
mutations: { mutationsAddCount(state, n = 0) { return (state.count += n) }, mutationsReduceCount(state, n = 0) { return (state.count -= n) } } //在组件的自定义事件内调用 this.$store.commit('mutationsAddCount',n); this.$store.commit('mutationsReduceCount',n); -
actions:异步操作。在组件中使用是$store.dispath(''")
actions: { actionsAddCount(context, n = 0) { console.log(context) return context.commit('mutationsAddCount', n) }, actionsReduceCount({ commit }, n = 0) { return commit('mutationsReduceCount', n) } } //在组件内自定义方法使用 this.$store.dispatch('actionsAddCount',n); this.$store.dispatch('actionsReduceCount',n); -
modules:store的子模块,为了开发大型项目,方便状态管理而使用的
// 新建module1.js export default { // namespaced:true, //开启namespace:true,该模块就成为命名空间模块了 state:{ str: 'store_a',//调用this.$store.state.mod_a.str }, getters:{...}, mutations:{...}, actions:{...} } //在store引入并配置 import ModA from './module1' export default new Vuex.Store({ modules: { mod_a: ModA } })
Vuex 和全局对象区别
Vuex 的状态存储是响应式的
不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation
-
使用Vue.prototype实现全局变量
//main.js Vue.prototype.global={a:0} //组件内调用,一个组件内改变该值,全局都改变 this.global.a -
在根节点中创建变量来实现全局变量
//在main.js new Vue({ …… data(){ return{ a:1 } }, …… }) //在子组件调用 $root.a