vuex结合localStorage的使用方法

源码地址:https://github.com/andyzhang0511/VuexStudy
vuex学习参考文章:https://www.cnblogs.com/chinabin1993/p/9848720.html
参考链接1
参考链接2
参考链接3

先看一下我的目录结构:
目录结构
1.main.js 入口 加载组件 初始化等

import Vue from 'vue'
import App from './App'
import store from '../store/index'

Vue.config.productionTip = false

new Vue({
  el: '#app',
  store,
  components: { App },
  template: '<App/>'
})

2.store.js—index.js 总文件

import Vue from "vue";
import Vuex from "vuex";
import state from './state';
import getters from './getters';
import mutations from './mutations';
import actions from './actions'
Vue.use(Vuex);

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})

3.store.js—state.js 状态数据存储

const state = {
    productList: [
        { name: "goods 1", price: 100 },
        { name: "goods 2", price: 200 },
        { name: "goods 3", price: 300 },
        { name: "goods 3", price: 400 }
    ],
    shopList: [
        { name: "shop 1", address: "aaaaa" },
        { name: "shop 2", address: "bbbbb" },
        { name: "shop 3", address: "ccccc" },
        { name: "shop 4", address: "ddddd" }
    ]
}
export default state

4.store.js—mutations.js (改变state.js里的值,顺便利用localStorage存储本地值,使得刷新浏览器后数据不会消失)

const mutations = {
    // reducePrice: (state, payload) => {
    //     return state.productList.forEach((product, index) => {
    //         localStorage.setItem('ceshi' + index, product.price)
    //         product.price -= payload;
    //     });
    // }
    reducePrice: (state, payload) => {
        state.productList.forEach((product, index) => {
            product.price -= payload;
        });
        localStorage.setItem('ceshi', JSON.stringify(state.productList))
        return state.productList
    }
}
export default mutations

5.store.js—actions.js

const actions = {
    // 提交的是mutation,可以包含异步操作
    // 这里我在两个方法中使用了两个不同的参数,一个是context,它是一个和store对象具有相同对象属性的参数。
    reducePriceAsync: (context, payload) => {
        setTimeout(() => {
            context.commit("reducePrice", payload);
        }, 2000);
    }
    // 也可以这么写  实际开发项目中我多数是这么写的
    // reducePriceAsync: ( {commit}, payload) => {
    //     setTimeout(() => {
    //         commit("reducePrice", payload);
    //     }, 2000);
    // }
}
export default actions

6.store.js—getters.js(使用getters来获取我们的state,因为它算是state的一个计算属性)

const getters = {
    getProductList: state => {
        return state.productList;
    },
    getShopList: state => {
        return state.shopList;
    },
    getSaledPrice: state => {
        localStorage.getItem('ceshi') ? 
        state.productList = JSON.parse(localStorage.getItem('ceshi')) : ''
        let saleProduct = state.productList.map(item => {
            // item.price = localStorage.getItem('ceshi'+index)
            console.log(item.price)
            return {
                name: "**" + item.name + "**",
                price: item.price / 2
            };
        });
        return saleProduct;
    }
}

export default getters

最后贴上两个组件的代码:
listOne

<template>
  <div class="list-one">
    <h1>list one</h1>
    <ul>
      <li v-for="(product, index) in getSaledPrice" :key="index">
        <p>名称:{{product.name}}</p>
        <p>价格:{{product.price}}</p>
      </li>
    </ul>
    <button @click="reducePrice(4)">降价</button>
    <button @click="reducePriceAsync(4)">异步降价</button>
  </div>
</template>

<script>
import { mapGetters, mapMutations, mapActions, commit, mapState } from "vuex";
export default {
  // data(){
  //   return {
  //     getSaledPrice: this.$store.getters.getSaledPrice
  //   }
  // },
  computed: {
    ...mapState(["productList"]),
    ...mapGetters(["getProductList", "getShopList", "getSaledPrice"])
  },
  methods: {
    // reducePrice(){
    //     this.$store.commit('reducePrice', 2)
    // },
    // reducePriceAsync(){
    //     this.$store.dispatch('reducePriceAsync', 2)
    // }
    // this.$store.commit(mutationName)是用来触发一个mutation的方法
    // this.$store.dispath(actionName)是用来触发一个actionName的方法
    ...mapMutations(["reducePrice"]),
    ...mapActions(["reducePriceAsync"])
  },
  mounted() {}
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}
.list-one {
  margin: 5px;
  padding: 8px;
  background: rgb(236, 199, 199);
}
ul {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  list-style-type: none;
  padding: 5px;
}
li {
  cursor: pointer;
  margin: 5px;
  width: 100%;
  flex: 1;
  text-align: center;
  color: #fff;
  background: rgb(107, 179, 207);
}
button {
  padding: 5px 15px;
  border: none;
  font-size: 14px;
}
</style>

listTwo

<template>
  <div class="list-two">
    <h1>list two</h1>
    <ul>
      <li v-for="(product, index) in getProductList" :key=index>
        <p>名称:{{product.name}}</p>
        <p>价格:{{product.price}}</p> 
      </li>
  </ul>
</div>
</template>

<script>
import {mapGetters} from 'vuex'

export default {
  computed: {
    ...mapGetters([
      'getProductList',
      'getShopList'
    ])
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
.list-two {
  margin: 5px;
  padding: 8px;
  background: rgb(252, 242, 199);
}
ul {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  list-style-type: none;
  padding: 5px;
}
li {
  cursor: pointer;
  margin:7px 0;
  width: 100%;
  flex: 1;
  background: #ccc;
}

</style>

关于localStorage的使用请见:
https://www.jianshu.com/p/2eb4ee865874
https://www.cnblogs.com/LChenglong/p/7497368.html

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值