Vuex的认识和简单应用(一)

一、vuex是一个专为vue.js应用程序开发的状态管理模式。

应用场景:
1、多个视图依赖于同一个状态
2、来自不同视图的行为需要变更同一个状态
此时,我们可以把组件的共享状态抽取出来,以一个全局单例模式管理

二、Vuex和单纯的全局对象有以下两点不同:

1、Vuex的状态存储是响应式的。当Vue组件从store中读取状态的时候,若store中的状态发生变化,那么相应的组件也会相应地得到高效更新。
2、不能直接改变store中的状态。改变store中的状态的唯一途径就是显示地提交(commit)mutation。

 

state:Vuex的状态存储
getter:vuex允许我们在store中定义"getter"(可以认为是store的计算属性)。就像计算属性一样,getter的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

 

mutation:更改vuex的store中的状态的唯一方法是提交mutation
mutation必须同步执行

 

action:action提交的事mutation,而不是直接变更状态

action可以包含任意异步操作

三、简单应用

store.js

 

 1 import Vue from 'vue'
 2 import Vuex from 'vuex'
 3 
 4 Vue.use(Vuex)
 5 
 6 export default new Vuex.Store({
 7   state: {//状态
 8     products:[
 9       {name:"马云",price:200},
10       {name:"马化腾",price:140},
11       {name:"马冬梅",price:20},
12       {name:"马蓉",price:10}
13     ]
14   },
15   getters:{
16     saleProducts:(state)=>{
17       var saleProducts = state.products.map(
18         product =>{
19           return {
20               name:'**'+ product.name +"**",
21               price:product.price / 2
22           }
23       });
24       return saleProducts;
25     }
26   },
27   mutations: {//触发事件改变数据
28     reducePrice:(state,payload)=>{
29       state.products.forEach(product=>{
30           product.price -= payload;
31       })
32     }
33   },
34   actions: {//异步mutations操作
35     reducePrice:(context,payload)=>{
36       setTimeout(function(){
37         context.commit('reducePrice',payload);
38       },2000)
39     }
40   }
41 })

 

Production.vue

 1 <template>
 2   <div id="product-list-one">
 3       <h2>Product List One</h2>
 4       <ul> 
 5           <li v-for="product in saleProducts" :key="product.name">
 6               <span class="name">{{product.name}}</span>
 7               <span class="price">${{product.price}}</span>
 8           </li>
 9       </ul>
10       <button @click="reducePrice(4)">商品降价</button>
11   </div>
12 </template>
13 <script>
14 import { mapGetters } from 'vuex'
15 import { mapActions } from 'vuex'
16 export default{
17   computed:{
18       products(){
19           return this.$store.state.products;
20       },
21       ...mapGetters([
22           "saleProducts"
23       ])
24     //   saleProducts(){
25     //       return this.$store.getters.saleProducts;
26     //   }
27   },
28   methods:{
29       /*reducePrice:function(amount){
30           //this.$store.commit('reducePrice');
31           this.$store.dispatch("reducePrice",amount);
32       }*/
33       ...mapActions([
34           "reducePrice"
35       ])
36   }
37 }
38 </script>
39 <style>
40 
41 </style>

 

posted @ 2019-08-01 15:36  典墨  阅读(421)  评论(0编辑  收藏  举报