Vuex

时间:2019-09-07
本文章向大家介绍Vuex,主要包括Vuex使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

vue中各个组件之间传值
父子组件
父组件-->子组件,通过子组件的自定义属性:props
子组件-->父组件,通过自定义事件:this.$emit('事件名',参数1,参数2,...);

非父子组件或父子组件
通过数据总数Bus,this.$root.$emit('事件名',参数1,参数2,...)

非父子组件或父子组件
更好的方式是在vue中使用vuex

方法1: 用组件之间通讯。这样写很麻烦,并且写着写着,估计自己都不知道这是啥了,很容易写晕。
方法2: 我们定义全局变量。模块a的数据赋值给全局变量x。然后模块b获取x。这样我们就很容易获取到数据

变量传值的演变形式:

Vuex

官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。可以想象为一个“前端数据库”(数据仓库),
让其在各个页面上实现数据的共享包括状态,并且可操作

Vuex分成五个部分:

1.State:单一状态树
2.Getters:状态获取
3.Mutations:触发同步事件
4.Actions:提交mutation,可以包含异步操作
5.Module:将vuex进行分模块

图解Vuex :

vuex使用步骤

安装
npm install vuex -S

创建store模块,分别维护state/actions/mutations/getters

store     index.js    state.js     actions.js     mutations.js     getters.js

在store/index.js文件中新建vuex的store实例,并注册上面引入的各大模块

 1 import Vue from 'vue'
 2 import Vuex from 'vuex'
 3 import state from './State'
 4 import getters from './Getters'
 5 import actions from './Actions'
 6 import mutations from './Mutations'
 7 
 8 Vue.use(Vuex)
 9 
10 const store = new Vuex.Store({
11      state,
12      getters,
13      actions,
14      mutations
15  })
16 
17  export default store

在main.js中导入并使用store实例

 1 // The Vue build version to load with the `import` command
 2 // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
 3 import Vue from 'vue'
 4 /* process.env.MOCK && require('@/mock') */
 5 import 'element-ui/lib/theme-chalk/index.css'
 6 import App from './App'
 7 import router from './router'
 8 import ElementUI from 'element-ui'
 9 import axios from '@/api/http'      
10 import VueAxios from 'vue-axios'
11 import store from './store'   
12 
13 
14 Vue.use(VueAxios,axios)
15 Vue.use(ElementUI)
16 Vue.config.productionTip = false
17 
18 /* eslint-disable no-new */
19 new Vue({
20   el: '#app',
21   data(){
22     return{
23       Bus:new Vue({
24 
25       })
26     }
27   },
28   router,
29   store,
30   components: { App },
31   template: '<App/>'
32 })

案列

state.js

1 export default{
2     resturantName:'K'
3 }

actions.js

 1 export default {
 2     setResturantNameByAsync: (context, payload) => {
 3         console.log('xxxx');
 4         setTimeout(() => {
 5             console.log('yyyy');
 6             console.log(payload)
 7             context.commit('setResturantName', payload);
 8         }, 3000)
 9         console.log('zzzz');
10     },
11     doAjax: (context, payload) => {
12         let _this=payload._this
13         let url = _this.axios.urls.SYSTEM_USER_DOLOGIN;
14         _this.axios.post(url, {}).then((respose) => {
15             console.log(respose);
16         }).catch(function(error) {
17             console.log(error);
18         });
19 }
20 
21 }

mutations.js

1 export default{
2     setResturantName:(state,payload)=>{
3         state.resturantName=payload.resturantName;
4     }
5 }

getters.js

1 export default{
2     getResturantName:(state)=>{
3         return state.resturantName;
4     }
5 }

VuexPage1.vue

 
 1 <template>
 2     <div>
 3         <h1>页面1:欢迎来到{{msg}}</h1>
 4         <button @click="buy">盘他(同步)</button>
 5         <button @click="buyAsync">盘他(异步)</button>
 6         <button @click="doAjax">。。。</button>
 7     </div>
 8 </template>
 9 
10 <script>
11     export default {
12         data() {
13             return {
14 
15             };
16         },
17         computed: {
18             msg() {
19                 return this.$store.state.resturantName;
20             }
21         },
22         methods: {
23             buy() {
24                 this.$store.commit('setResturantName', {
25                     resturantName: 'T'
26                 });
27             },
28             buyAsync() {
29                 this.$store.dispatch('setResturantNameByAsync', {
30                     resturantName: 'V'
31                 });
32             },
33             doAjax() {
34                 this.$store.dispatch('doAjax', {
35                     _this:this    
36                 });
37             }
38         }
39     }
40 </script>
41 
42 <style>
43 </style>

VuexPage2.vue

 1 <template>
 2     <div>
 3         <h1>页面2:欢迎来到{{msg}}</h1>
 4     </div>
 5 </template>
 6 
 7 <script>
 8     export default {
 9         data() {
10             return {
11 
12             };
13         },
14         computed: {
15             msg() {
16                 return this.$store.getters.getResturantName;
17             }
18         }
19     }
20 </script>
21 
22 <style>
23 </style>

vuex的核心概念:store、state、getters、mutations、actions

store
每一个Vuex应用的核心就是store(仓库),store基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
const store = new Vuex.Store({
state, // 共同维护的一个状态,state里面可以是很多个全局状态
getters, // 获取数据并渲染
actions, // 数据的异步操作
mutations // 处理数据的唯一途径,state的改变或赋值只能在这里
})

state(保存数据的容器)
状态,即要全局读写的数据

1    const state = {
2         resturantName:'飞歌餐馆'
3       };
4 
5       this.$store.state.resturantName;//不建议

getters(getXxx)获取数据并渲染

1 const getters = {
2        resturantName: (state) => {
3          return state.resturantName;
4        }
5      }; 

getters将state中定义的值暴露在this.$store.getters对象中,我们可以通过如下代码访问

1   this.$store.getters.resturantName

state状态存储是响应式的,从store实例中读取状态最简单的方法就是在计算属性中返回某个状态,如下:

1 computed: {
2             resturantName: function() {
3               return this.$store.getters.resturantName;
4             }
5           }

mutations(setXxx)处理数据的唯一途径,state的改变或赋值只能在这里

1 export default {
2         // type(事件类型): 其值为setResturantName
3         // payload:官方给它还取了一个高大上的名字:载荷,其实就是一个保存要传递参数的容器
4     setResturantName: (state, payload) => {
5           state.resturantName = payload.resturantName;
6     }
7       }

mutations中方法的调用方式不能直接调用this.$store.mutations.setResturantName('KFC'),必须使用如下方式调用:

1 this.$store.commit(type,payload);

把载荷和type分开提交

1  store.commit('setResturantName',{
2              resturantName:'KFC'
3            })

载荷和type写到一起

1 store.commit({
2             type: 'setResturantName',
3             resturantName: 'KFC'
4           })
5            

一定要记住,Mutation 必须是同步函数。为什么呢?异步方法,我们不知道什么时候状态会发生改变,所以也就无法追踪了如果我们需要异步操作,Mutations就不能满足我们需求了,这时候我们就需要Actions了

1 mutations: {
2             someMutation (state) {
3               api.callAsyncMethod(() => {
4                 state.count++
5               })
6             }
7            } 

actions

数据的异步(async)操作

1 export default {
2      setResturantNameByAsync: function(context, payload) {
3        setTimeout(() => {
4          context.commit('setResturantName', payload);//Action提交的是mutation
5        }, 3000);
6      }
7    }

Action类似于 mutation,不同在于:

1.Action提交的是mutation,而不是直接变更状态
2.Action可以包含任意异步操作
3.Action的回调函数接收一个 context 上下文参数,注意,这个参数可不一般,它与 store 实例有着相同的方法和属性
但是他们并不是同一个实例,context 包含:
1. state、2. rootState、3. getters、4. mutations、5. actions 五个属性
所以在这里可以使用 context.commit 来提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

 Vuex的管理员Module 

其实是为了搞定那些稍微大型复杂一点的项目,避免 store 里面的数据太多。这样的话,store 对象就会变得相当的臃肿,非常难管理Module应运而生

 1 const moduleA = {
 2   state: { ... },
 3   mutations: { ... },
 4   actions: { ... },
 5   getters: { ... }
 6 }
 7 
 8 const moduleB = {
 9   state: { ... },
10   mutations: { ... },
11   actions: { ... }
12 }
13 
14 const store = new Vuex.Store({
15   modules: {
16     a: moduleA,
17     b: moduleB
18   }
19 })

原文地址:https://www.cnblogs.com/xcn123/p/11479351.html