1.Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。简单直白的理解:至关于全局变量,但和全局变量又有两点不一样。vue
(1)Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时,若 store 中的状态变化,那么相应的组件也更新。 (2)不能直接改变 store 中的状态。改变 store 中的状态的惟一途径就是显式地提交(commit) mutations。2.中大型项目使用能很好解决组件间混乱的多层级数据传递通讯问题。webpack
State
池 (数据源)Getter
查 (获取数据源的数据,至关于vue的computed)Mutation
修改 (真正修改的动做 同步)Action
触发修改行为(多配合异步使用)Module
能够拥有多个数据源(数据池)git
# 选webpack模板 搭建在一个叫pro_vuex的文件夹里 $ vue init webpack pro_vuex
# 进入项目安装并保存到依赖上 $ npm i vuex -S
. ├── App.vue //父组件 ├── main.js //入口文件 ├── `store ` //状态管理文件夹 | ├── modules //多个数据源(数据池) │ └── `index.js` ├── components │ └── HelloWorld.vue //子组件 ├── router //路由 │ └── index.js └── assets └── logo.png
建立仓库 /store/index.js
import引入插件;Vue.use使用插件;new Vuex.Store 实例化一个Vuex对象;暴露出去github
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); // 实例化Vuex,建立一个仓库 const store = new Vuex.Store({ // 数据池 state: { count: 0, author: 'tom' }, // 能够对数据操做后返回 至关于vue里面的computed getters:{ userName(state){ return state.author +' hello'; } }, // 修改数据的方法 同步 mutations: { // 修改数据的方法。 参数一固定state 后面随意 increment(state,num) { state.count+=num } }, // 修改数据的异步 方法 actions:{ // 参数一 执行上下文 incrementAction(context,num) { context.commit("increment",num); //等同于在组件里面this.$store.commit("increment",18) } } }) // 暴露出去 export default store
入口文件引入仓库 main.js
单页面应用程序中 在入口文件引用,其下子组件就全都能获取调用。web
import Vue from 'vue' import App from './App' import router from './router' import store from './store/index.js' // 引入仓库 Vue.config.productionTip = false new Vue({ el: '#app', router, store, // 挂载仓库 key和value同样时 能够简写 components: { App }, template: `<App/>` })
任意组件读取修改仓库 示例在components/HelloWorld.vuevuex
<template> <div class="hello"> <h1>{{ msg }}</h1> <h4>年龄: {{my_age}} </h4> <h4>用户名:{{name}} </h4> <h4>打招呼:{{userName}}</h4> <input type="button" @click="add_mutation" value="mutation方法修改年龄my_age"> <br/>~~~~ <input type="button" @click="add_action" value="action方法修改年龄my_age"> </div> </template> <script> export default { name: 'HelloWorld', data () { return { msg: '来自子组件的亲切问候' } }, computed:{ my_age(){ return this.$store.state.count }, name(){ return this.$store.state.author }, userName(){ return this.$store.getters.userName; //经过getters方法的 读取也要区分处理 } }, methods:{ add_mutation(){ this.$store.commit("increment",18) //调用store/index.js里面经过mutations定义的increment方法 }, add_action(){ this.$store.dispatch("incrementAction",12); } } } </script> <style scoped> input { line-height: 1.6rem; margin: 10px; } </style>
当一个组件须要获取多个状态时候,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,咱们能够使用mapState
辅助函数帮助咱们生成计算属性。mapState
函数返回的是一个对象。npm
import { mapState } from "vuex"; computed: { ...mapState({ author: state => state.author, }) }
mark一下 仅供参考 欢迎更正补充 Thanksapp
参考资料:
官网: https://vuex.vuejs.org/zh/
npm_vuex: https://www.npmjs.com/package...
source: https://github.com/Wscats/vue...异步