欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vuex管理dialog、toast等常見(jiàn)全局性組件狀態(tài)時(shí)唯一性的問(wèn)題解決

 更新時(shí)間:2022年11月14日 10:20:35   作者:ychizzz  
工作中經(jīng)常會(huì)用到類似于?dialog、toast、popover?等一些狀態(tài)提示組件,這篇文章主要介紹了Vuex管理dialog、toast等常見(jiàn)全局性組件狀態(tài)時(shí)唯一性的問(wèn)題,需要的朋友可以參考下

前言

工作中經(jīng)常會(huì)用到類似于 dialog、toastpopover 等一些狀態(tài)提示組件。對(duì)于這種全局性的組件,通常會(huì)用到 vuex 來(lái)管理組件的信息。這樣的好處是代碼維護(hù)起來(lái)更加友好,但是也需要考慮唯一性的問(wèn)題。

場(chǎng)景

以 dialog 為例,唯一性問(wèn)題是指當(dāng)頁(yè)面中有多處內(nèi)容調(diào)用了同一個(gè)事件,而這個(gè)事件都是修改了全局的 vuex 狀態(tài),從而導(dǎo)致頁(yè)面中多次依賴于全局狀態(tài)的組件會(huì)同時(shí)展示。例如以下場(chǎng)景:

要解決這樣的問(wèn)題,需要在 state 中設(shè)置一個(gè) id 變量,同時(shí)給組件調(diào)用的時(shí)候傳一個(gè) id,在展示組件之前判斷兩個(gè) id 是否一致,一致才展示。

代碼

store.js

const state = {
  id: "", // 用于判斷唯一性
  isShow: false,
};

const mutations = {
  setShowDialog(state, data) {
    state.id = data.id;
    state.isShow = true;
  },
};

export default {
  namespaced: true, // 解決命名沖突(使用時(shí)需要備注模塊名)
  state,
  mutations,
};

dialog.vue

<!-- 全局dialog組件 -->
<template>
  <div v-if="isShowCurrentDialog">
    <!-- 組件邏輯省略 -->
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
export default {
  props: {
    currId: {
      type: String,
      default: "",
    },
  },
  computed: {
    ...mapState(["id"]),
    isShowCurrentDialog() {
      if (this.currId) {
        return this.id === this.currId ? this.isShow : false;
      } else {
        return this.isShow;
      }
    },
  },
};
</script>

xxx.vue

<!-- 調(diào)用dialog的組件 -->
<template>
  <div>
    <ul>
      <!-- 模擬同時(shí)多個(gè)dialog調(diào)用場(chǎng)景 -->
      <li v-for="item in listData" :key="item.name" @click="setShowDialog({ id: item.name })">
        <Dialog :id="item.name" />
      </li>
    </ul>
  </div>
</template>
<script>
import { mapMutations } from "vuex";
export default {
  data() {
    return {
      listData: [
        {
          name: "aaa",
        },
        {
          name: "bbb",
        },
        {
          name: "ccc",
        },
      ],
    };
  },
  methods: {
    ...mapMutations(["setShowDialog"]),
  },
};
</script>

到此這篇關(guān)于Vuex管理dialog、toast等常見(jiàn)全局性組件狀態(tài)時(shí)唯一性的問(wèn)題的文章就介紹到這了,更多相關(guān)Vuex全局性組件狀態(tài)時(shí)唯一性內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論