vue3 使用vuex

1.前言

vuex作為 vue中最流行的狀態(tài)管理工具,在vue3版本使用的時(shí)候也是有些注意事項(xiàng)的 總結(jié)如下


2. store

只是講解和 v2不同的地方,store 文件v3一樣
這里這個(gè)store就不拆分了,看起來(lái)費(fèi)勁

import { createStore } from 'vuex'

export default createStore({
  state: {
    num: 1,
    carList: [
      { carName: "毛豆Y", price: 27, range: 568 },
      { carName: "極氪001", price: 28, range: 620 },
      { carName: "零跑C11", price: 19, range: 520 },
      { carName: "比亞迪漢", price: 23, range: 610 }
    ],
    userInfo: {}
  },
  getters: {
    doubleNum(state) {
      return Math.pow(state.num, 2)
    },
    userVipList(state) {
      return state.carList.filter(v => v.range > 600)
    }
  },
  mutations: {
    increase(state, { payload = 10 }) {
      state.num += payload
    },
    setCarList(state, { payload }) {
      return state.carList = payload
    },
    delList(state, index) {
      state.carList.splice(index, 1);
    },
    updateUserInfo(state, obj) {
      state.userInfo = obj
      console.log("存儲(chǔ)成功",state)
    },

  },
  actions: {
    getActionList(context) {
      // 模擬異步請(qǐng)求
      setTimeout(() => {
        context.commit("setCarList", { payload: [{ carName: "極氪001", price: 28, range: 620 },] })
      }, 1000)
    },
    delCarList(context,index) {
      setTimeout(() => {
        //觸發(fā)mutations中的方法 變更狀態(tài)
        context.commit("delList", index);
      }, 1000)
    }
  },
  modules: {
  }
})


3.不使用輔助函數(shù)

3.1.1 直接訪問(wèn) store state

直接使用 和v2用法一樣

      <h1>vuex數(shù)據(jù)-state:{{$store.state.num}}</h1>
    <ul>
        <li v-for="item in $store.state.carList" :key="item">{{item.carName}}</li>
      </ul>

3.1.2 計(jì)算屬性 同名

 computed:mapState(["num"]),

這種寫(xiě)法 就只能使用 num的名字

3.1.3 計(jì)算屬性 computed 別名-1

computed:{
    num(){
      return this.$store.state.num
    }
  },

這種方式 新的計(jì)算屬性的名字也可以 換個(gè)名字不叫 num


3.1.4 計(jì)算屬性 computed 別名-2

 computed:mapState({
    otherNum:state=>state.num,
  }),

3.1.5 計(jì)算屬性 computed 別名-3

 computed:mapState({
    n:"num"
  }),

3.2 訪問(wèn) store getter

<h1>vuex-getters:{{$store.getters.doubleNum}}</h1>

3.3 mutation

 <h1>vuex數(shù)據(jù)修改-mutation: <button @click="add">增加</button></h1>

<script setup>
import {useStore} from 'vuex'
let store = useStore()
let add = ()=>{
    store.commit("increase",{payload:100})
}
</script>

直接使用了 setup


3.4 action

<h1>vuex數(shù)據(jù)修改-action: <button @click="changeCar">修改</button></h1>

let changeCar = ()=>{
    store.dispatch("getActionList")
}

4. 輔助函數(shù)

4.1 直接上 模板

<template>
  <div>
    <h1>vuex-輔助函數(shù)</h1>
    <h1>vuex數(shù)據(jù)-state:{{ num }}</h1>

    <h1>vuex數(shù)據(jù)修改-mutation: <button @click="add">增加</button></h1>
    <h1>vuex數(shù)據(jù)修改-action: <button @click="changeCar">修改</button></h1>
    <ul>
      <li v-for="(item, index) in $store.state.carList" :key="item">
        {{ item.carName }}
        <button @click="$store.dispatch('delCarList', index)">×</button>
      </li>
    </ul>
    <hr />
    <h1>vuex-getters:{{ doubleNum }}</h1>
  </div>
</template>

4.2 邏輯

<script>
import { mapState, mapMutations, mapGetters, mapActions } from "vuex";
export default {
  computed: {
    ...mapState(["num"]),
    ...mapGetters(["doubleNum"]),
    // 組件自己的計(jì)算屬性
  },
  methods: {
    // ...mapMutations(["increase"]),
    ...mapActions({
      myIncrease: "increase", //如果名字和本組件名字沖突 可取別名
    }),
    ...mapMutations(["getActionList"]),
    add() {
      //直接用
      this.myIncrease({ payload: 1 });
    },
    changeCar() {
      this.$store.dispatch("getActionList", index);
    },
  },
};
</script>


5. 實(shí)際使用注意數(shù)據(jù)響應(yīng)式

<script setup>
import { onMounted, reactive } from "vue";
import {useStore} from 'vuex'
import axios from "axios";
let userInfo = reactive({});
const store = useStore()

let login = () => {
  axios
    .post("/xx/xx/cellphone", {
      phone: 186xxxx8753,
      password: "123456",
    })
    .then((res) => {
      if (res.data.code == 200) {
        Object.assign(userInfo, res.data);
        console.log("userInfo", userInfo);
        store.commit("updateUserInfo",userInfo)
      } else {
        alert("登錄失敗");
      }
    });
};
</script>

Object.assign(targetObj,obj) 賦值一個(gè)對(duì)象到目標(biāo)對(duì)象
返回修改后的目標(biāo)對(duì)象

參考資料


初心

我所有的文章都只是基于入門(mén),初步的了解;是自己的知識(shí)體系梳理;
如果能幫助到有緣人,非常的榮幸,一切為了部落的崛起;
共勉
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容