1. 程式人生 > >Element-UI訊息提示元件Message在Vuex中的呼叫實現

Element-UI訊息提示元件Message在Vuex中的呼叫實現

在最近的專案開發中,前端部分使用 Vue 開發,整個頁面基於 Element-UI 實現。

由於是單頁面多元件應用,使用了 Vuex 做狀態管理。

為了頁面互動的友好和風格的統一,訊息提醒使用 Element-UIMessage訊息提示, 不使用 window.alert

this.$message({
     showClose: true,
     message: '警告哦,這是一條警告訊息',
     type: 'warning'
   });

然而,系統使用了 Vuex 做狀態管理,在 actions 中的方法中,this 並沒有 $message 的引用,後續還需研究下相關的物件之間的關係,但是這次從另外一個角度,對這個問題進行了考慮。

通過這個思路,便於我們更靈活的控制js指令碼。這裡通過 Message訊息提示 元件來演示。

我們知道 Vuex 的狀態管理是通過資料進行頁面管理的,也就是說所有的頁面變化其實都是資料的變化引起的。

state 中新增屬性:

const state = {
   msg:{type:"success", content:"", count:0},
   //其他屬性...
}

新建一個 Msg.vue 的元件:

<template>
  <div id="msg-dependencies" v-if="msgCount == 0">
  </div
>
</template> <script> export default { data(){ return { } }, computed:{ msgCount(){ var type = this.$store.state.msg.type; var msg = this.$store.state.msg.content; if(msg !== "") { var param = { "type"
:type, message:msg }; console.log("message param:",param) this.$message(param); } return this.$store.state.msg.count; } } }
</script>

元件內的屬性 msgCountcomputed 屬性,僅僅是為了跟蹤 statemsg.count 的變更,並無實際意義。

mutations 中定義訊息觸發方法:

export const showInfoMsg = (state, content) => {
  console.log("show info msg:", content);
  state.msg.type = "info";
  state.msg.content = content;
  state.msg.count = state.msg.count + 1;
}

每次呼叫都會觸發 msg.count 的變更,進行反饋到 Msg.vue 元件中,算是vue為我們提供的一種回撥函式。

元件內呼叫

this.$store.commit("showInfoMsg","刪除成功!");

或者actions內執行類似呼叫

context.commit("showInfoMsg","刪除成功!");