xinggevip

Vue2.x Cli3.x vuex的安装和使用
安装vuex到项目中,找到当前项目npm install vuex --save 创建store.js在src目录...
扫描右侧二维码阅读全文
08
2019/06

Vue2.x Cli3.x vuex的安装和使用

安装vuex到项目中,找到当前项目

npm install vuex --save

创建store.js

在src目录创建store文件夹,在此文件夹下创建store.js文件

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const store = new Vuex.Store({
    state:{
        products:[
            {
              name:"马云",
              price:200
            },
            {
              name:"马化腾",
              price:100
            },
            {
              name:"马冬梅",
              price:50
            },
            {
              name:"马蓉",
              price:10
            }
          ]
    },
    getters:{
        soleproducts:(state) =>{
            var soleproducts = state.products.map((product) =>{
                return {
                    name:"**" + product.name + "**",
                    price:product.price
                }
            });
            return soleproducts;
        }
    },
    mutations:{
        changedata:(state) =>{
            return state.products.forEach(element => {
                element.price -= 1;
            });
        }
    }

})

main.js导入store.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import {store} from './store/store'

Vue.config.productionTip = false

new Vue({
  store:store,
  router,
  render: h => h(App)
}).$mount('#app')

组件引用store中的数据和方法

<template>
  <div class="productlistone">
    <h1>福布斯排行榜</h1>
    <ul v-for="product in soleproducts" :key="product.value">
        <li>
          <span class="name">{{product.name}}</span>
          <span class="price">${{product.price}}</span>
        </li>
    </ul>
    <button v-on:click="caozuo">getters操作</button>
    <button v-on:click="mcaozuo">mutations操作</button>
  </div>
</template>

<script>
export default {  
    // props:['products'],
    
    computed:{
      // products(){
      //   return this.$store.state.products;
      // },
      soleproducts(){
        // var soleproducts = this.$store.state.products.map((product) =>{
        //     return {
        //       name:"**" + product.name + "**",
        //       price:"**" + product.price + "**"
        //     }
        // });
        // return soleproducts;

        // 执行store中的方法获取数据----getters
        return this.$store.getters.soleproducts;
      }
    },
    methods:{
      // 获取store数据----state
      caozuo:function(){
        return this.$store.state.products.forEach(element => {
          element.price -= 1;
        });
      },
      // 执行store中的方法处理数据----mutations
      mcaozuo:function(){
        this.$store.commit('changedata');
      }
    }
}
</script>
Last modification:June 8th, 2019 at 10:28 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment