vuex的一些学习

刚开始学vuex看文档看的一脸懵逼,故而网上各种查找资料,视频去观看学习,虽然看了很多还是很蒙圈,最近看了一个讲vuex的视频还有一个 类似的简书文档从中学到了很多,慢慢理清了头绪,至此记录一下,共同学习共同进步。。。

1、安装下载vuex    npm install vuex --save

2、我们先来了解一下vuex官网的一些介绍,有一个流程图很形象的介绍了vuex中的各种属性直接的联系,以及vuex主要的作用

 

这个图刚开始我是看不懂的,不是很明白他们之间的关系,现在就来梳理一下

一、如何引入vuex

前面我们安装了vuex,但是如何引入呢?

首先我们现在文件夹目录下建一个store文件夹,然后再建一个store.js文件,在这个文件里面引入vuex

//store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex)

然后在main.js文件里面引入store.js文件,就可以使用vuex了

//main.js
import Vue from 'vue' import App from './App.vue' import {store} from './store/store' new Vue({ store:store, el: '#app', render: h => h(App) })

  

二、先来看一下没用vuex进行数据传递的代码,这个使用父子之间的props进行传值

//App.vue中的初始化代码

<template>
<div id="app">
    <product-list-one v-bind:products="products"></product-list-one>
    <product-list-two v-bind:products="products"></product-list-two>
</div>
</template>

<script>
import ProductListOne from './components/ProductListOne.vue'
import ProductListTwo from './components/ProductListTwo.vue'

export default {
    name: 'app',
    components: {
        'product-list-one': ProductListOne,
        'product-list-two': ProductListTwo
    },
    data () {
        return {
            products: [
                 {name:'权杖',price:800},
             {name:'纪梵希',price:400},
             {name:'迪奥',price:360},
             {name:'圣罗兰',price:320},
            ]
        }
    }
}
</script>

<style>
body{
    font-family: Ubuntu;
    color: #555;
}
</style>
//ProductListOne.vue
<template>
    <div id="product-list-one">
        <h2>Product List One</h2>
        <ul>
            <li v-for="product in products">
                <span class="name">{{ product.name }}</span>
                <span class="price">${{ product.price }}</span>
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    props: ['products'],
    data () {
        return {

        }
    }
}
</script>

<style scoped>
#product-list-one{
    background: #FFF8B1;
    box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
    margin-bottom: 30px;
    padding: 10px 20px;
}
#product-list-one ul{
    padding: 0;
}
#product-list-one li{
    display: inline-block;
    margin-right: 10px;
    margin-top: 10px;
    padding: 20px;
    background: rgba(255,255,255,0.7);
}
.price{
    font-weight: bold;
    color: #E8800C;
}
</style>
//ProductListTwo.vue
<template>
    <div id="product-list-two">
        <h2>Product List Two</h2>
        <ul>
            <li v-for="product in products">
                <span class="name">{{ product.name }}</span>
                <span class="price">${{ product.price }}</span>
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    props: ['products'],
    data () {
        return {
            
        }
    }
}
</script>

<style scoped>
#product-list-two{
    background: #D1E4FF;
    box-shadow: 1px 2px 3px rgba(0,0,0,0.2);
    margin-bottom: 30px;
    padding: 10px 20px;
}
#product-list-two ul{
    padding: 0;
    list-style-type: none;
}
#product-list-two li{
    margin-right: 10px;
    margin-top: 10px;
    padding: 20px;
    background: rgba(255,255,255,0.7);
}
.price{
    font-weight: bold;
    color: #860CE8;
    display: block;
}
</style>

 

属性一:State

这个属性简单的说就是放数据的用的容器,你可以把你需要公用的数据放到这个属性里面,然后在每个需要的页面用store.state.products去调用它,代码如下

//store.js
import Vue from 'vue'
import Vuex from 'vuex'
 
 Vue.use(Vuex)
 export const store = new Vuex.Store({
     state:{
         products:[
             {name:'权杖',price:800},
             {name:'纪梵希',price:400},
             {name:'迪奥',price:360},
             {name:'圣罗兰',price:320},
         ]
     }


 })

当然,我们用了vuex中的state相应的组件ProductListOne和ProductListTwo也要相应改变,两个文件需要改的都一样

<template>
  <div id="product-list-one">
    <h2>Product List One</h2>
    <ul>
      <li v-for="product in saleProducts">
        <span class="name">{{product.name}}</span>
        <span class="price">${{product.price}}</span>
      </li>
    </ul>
  
  </div>
</template>

<script>



export default {
  data () {
        return {
            saleProducts : this.$store.state.products //获取store中state的数据
        }
    }
 
}
</script>

 

 

属性二:Getters

这个属性就相当于一个方法去改变数据,这里我让每个数据都打八折,代码如下

//store.js
import Vue from 'vue'
import Vuex from 'vuex'
 
 Vue.use(Vuex)
 export const store = new Vuex.Store({
     state:{
         products:[
             {name:'权杖',price:800},
             {name:'纪梵希',price:400},
             {name:'迪奥',price:360},
             {name:'圣罗兰',price:320},
         ]
     },
     getters:{
         salesProducts:(state)=>{
             var salesProducts = state.products.map(
              product=>{
                return{
                  name:'**'+product.name+'**',
                  price:product.price*0.8
                };
              });
        return salesProducts;
         }
     },



 })
<!-- productListTwo.vue -->
<script>
export default {
 /* data () {
        return {
            saleProducts : this.$store.state.products //获取store中state的数据
        }
    }*/
      computed:{
      salesProducts(){
        return this.$store.getters.salesProducts;//使用getters调取改变的数据
      }
    }
}
</script>

属性三:Mutations

该属性主要是用于你触发事件是需要使用Mutations,如果我们需要实现点击降价的话,就需要这个属性,调用this.$store.commit('')

//store.js
import Vue from 'vue'
import Vuex from 'vuex'
 
 Vue.use(Vuex)
 export const store = new Vuex.Store({
     state:{
         products:[
             {name:'权杖',price:800},
             {name:'纪梵希',price:400},
             {name:'迪奥',price:360},
             {name:'圣罗兰',price:320},
         ]
     },
     getters:{
         salesProducts:(state)=>{
             var salesProducts = state.products.map(
              product=>{
                return{
                  name:'**'+product.name+'**',
                  price:product.price*0.8
                };
              });
        return salesProducts;
         }
     },

   mutations:{
       reducePrice:state=>{
            state.products.forEach(product=>{
          product.price-=10;
        })
       }
   }

 })
<template>
  <div id="product-list-one">
    <h2>Product List One</h2>
    <ul>
      <li v-for="product in salesProducts">
        <span class="name">{{product.name}}</span>
        <span class="price">${{product.price}}</span>
      </li>
    </ul>
  <button @click="reducePrice">商品打折</button>
  </div>
</template>

<script>



export default {
  /*data () {
        return {
            saleProducts : this.$store.state.products //获取store中state的数据
        }
    },*/
    computed:{
      salesProducts(){
        return this.$store.getters.salesProducts;
        /*var saleProducts = this.$store.state.products.map(
              product=>{
                return{
                  name:'**'+product.name+'**',
                  price:product.price*0.8
                }
              })
        return saleProducts;*/
      }
    },
    methods:{
      reducePrice:function(){
        /*this.$store.state.products.forEach(product=>{
          product.price-=10;
        })*/
        this.$store.commit('reducePrice');
      }
    }
 
}
</script>

 

属性四:Actions

该属性类似Mutations不同的是:$store.dispatch("",amount)

Actions提交Mutations,

Actions可以同时提交异步的方法

//store.js
import Vue from 'vue'
import Vuex from 'vuex'
 
 Vue.use(Vuex)
 export const store = new Vuex.Store({
     state:{
         products:[
             {name:'权杖',price:800},
             {name:'纪梵希',price:400},
             {name:'迪奥',price:360},
             {name:'圣罗兰',price:320},
         ]
     },
     getters:{
         salesProducts:(state)=>{
             var salesProducts = state.products.map(
              product=>{
                return{
                  name:'**'+product.name+'**',
                  price:product.price*0.6
                };
              });
        return salesProducts;
         }
     },

   mutations:{
       reducePrice:(state,payload)=>{
            state.products.forEach(product=>{
          product.price-=payload;
        })
       }
   },
   actions:{
       reducePrice:(context,payload)=>{
           context.commit("reducePrice",payload);
       }
   }

 })
 methods:{
      reducePrice:function(amount){
        /*this.$store.state.products.forEach(product=>{
          product.price-=10;
        })*/
        //this.$store.commit('reducePrice');
        this.$store.dispatch("reducePrice",amount);//dispatch分发
      }
    }

 

属性五:mapGetters,mapActions

先安装  npm install babel--preset-stage-2 --save-dev

然后在你需要的页面引入mapGetters,mapActions,这个主要是用在你的store.js里面可能有很多个Getters和Actions时,比较方便简洁的一种写法

<script>
import {mapGetters} from "vuex"  //引入mapGetters
import {mapActions} from "vuex"   //引入mapActions

export default {
  
    computed:{
        ...mapGetters([
           "salesProducts"
        ])
   
    },
    methods:{
  
      ...mapActions([
        "reducePrice"
        ])
    }
 
}
</script>

 

 

 

posted @ 2019-02-25 19:32  kingsnowcan  阅读(166)  评论(0编辑  收藏  举报