vuex 的使用

//store/index.js
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
// 表示商品添加
const Add = 'ADD'
export default new Vuex.Store({
  state: {
    goods: [
      {
        id: 1,
        buyCount: 1,
        title: "wywuiqiyiwyqi",
        price: 55,
      },
      {
        id: 2,
        buyCount: 1,
        title: "dlkajdlal",
        price: 10,
      },
    ],
    totalPrice: 0,
    totalNum: 0,
  },
  getters: {
    goodsObj: (state) => {
      return state.goods;
    },
    goodsObjId: (state) => (id: any) => {
      return state.goods.filter((item) => item.id === id);
    },
  },
  mutations: {
    [Add](state, {index}) {
      state.goods[index].buyCount++;
      state.totalNum++;
      state.totalPrice += state.goods[index].price;
    },
  },
  actions: {
    increment({commit},payload){
      commit(Add,payload)
    }
  },
  modules: {},
});

// xxx页面

<template>
  <div>
    <div v-for="(item, index) in goods" :key="item.id">
      {{ item.title }}

      <span @click="handelAdd(index)">+</span>
      <input type="text" v-model="item.buyCount" />
      <span>-</span>
    </div>
    <p>总价:{{ totalPrice }}</p>
    <p>总数:{{ totalNum }}</p>
  </div>

<div v-for="item in this.$store.state.list" :key="item.id">
        {{ item.name }}
        <img :src="item.pic">
    </div>

<div v-for="item in goodss" :key="item.id">
  {{ item.price }}
</div


</template>

<script>
import { mapState,mapGetters } from "vuex";
export default {
  data() {
    return {};
  },
    computed: {
    // goods(){
    //     return this.$store.state.goods
    // },
    ...mapState(["goods"]),
    ...mapState({
      totalPrice: (state) => state.totalPrice,
      totalNum: (state) => state.totalNum,
   
      ...mapGetters(['goodsObj']),
      ...mapGetters({
        goodss:'goodsObj'
      })
    }),
  },
  mounted() {
    console.log(this.$store.getters.goodsObj);
    console.log(this.$store.getters.goodsObjId(1));

       axios.get('http://localhost:3000/goods').then(res=>{
      console.log(res);
     this.$store.state.list = res.data    

  },
  methods: {
    handelAdd(index) {
    //   this.$store.commit("add", index);

    // this.$store.commit({
    //     type:'ADD',
    //     index
    // });
    this.$store.dispatch('increment',{index})
    },
  },
};
</script>

<style lang="scss" scoped></style>

### Vuex 使用指南及实现状态管理示例 Vuex 是一个专为 Vue.js 应用设计的状态管理库,它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化[^1]。以下是关于 Vuex 的核心概念和使用方法的详细说明。 #### 1. 核心概念 Vuex 的核心概念包括以下几个部分: - **State**:用于存储共享的状态数据。 - **Getter**:类似于 Vue 组件中的计算属性,用于从 state 中派生出一些状态。 - **Mutation**:用于同步地修改 state 的方法。 - **Action**:类似于 mutation,但可以包含异步操作,最终会提交 mutation 来改变 state。 - **Module**:将 store 分割成模块,使代码更易于维护。 #### 2. 创建 Vuex Store 在项目中创建一个 `store.js` 文件,定义 Vuex 的 store: ```javascript // store.js import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); export default new Vuex.Store({ state: { count: 0 // 示例状态 }, getters: { doubleCount(state) { return state.count * 2; // 计算属性示例 } }, mutations: { increment(state) { state.count++; // 同步修改状态 } }, actions: { incrementAsync({ commit }) { setTimeout(() => { commit('increment'); // 异步操作后提交 mutation }, 1000); } } }); ``` #### 3.Vue 实例中引入 Store 在 `main.js` 文件中引入并挂载 store: ```javascript // main.js import Vue from 'vue'; import App from './App.vue'; import store from './store'; new Vue({ store, // 挂载 store render: h => h(App) }).$mount('#app'); ``` #### 4. 在组件中使用 Vuex 通过 `mapState`、`mapGetters`、`mapMutations` 和 `mapActions` 辅助函数简化对 Vuex 的访问: ```javascript <template> <div> <p>Count: {{ count }}</p> <p>Double Count: {{ doubleCount }}</p> <button @click="increment">Increment</button> <button @click="incrementAsync">Increment Async</button> </div> </template> <script> import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'; export default { computed: { ...mapState(['count']), // 映射 state 到本地计算属性 ...mapGetters(['doubleCount']) // 映射 getter 到本地计算属性 }, methods: { ...mapMutations(['increment']), // 映射 mutation 到本地方法 ...mapActions(['incrementAsync']) // 映射 action 到本地方法 } }; </script> ``` #### 5. 状态持久化 未进行持久化配置可能导致状态丢失、数据不一致或重复操作等问题[^3]。可以通过插件如 `vuex-persistedstate` 实现状态持久化: ```javascript // store.js import createPersistedState from 'vuex-persistedstate'; export default new Vuex.Store({ state: { count: 0 }, plugins: [createPersistedState()] // 添加持久化插件 }); ``` 这样,即使页面刷新,状态也会被保存到 localStorage 或 sessionStorage 中。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值