vue 通過router 解決動態(tài)組件切換刷新問題

以前對于動態(tài)組件的切換,都是在index.vue下的子組件中通過this.$parent.方法名,來直接調(diào)用父組件的方法實現(xiàn)組件切換,在vue中是不提倡這樣使用的。可以使用this.$emit('方法名',{參數(shù)}),將事件綁定在父組件上面來使用。

image.png

另一種方法便是我要說的,通過vue路由來實現(xiàn)動態(tài)組件的切換。在上面index.vue文件中包含動態(tài)組件list、edit、add三個組件,每個組件代表一個頁面,頁面加載后的默認組件是list,edit和add都是通過list頁面進入。(動態(tài)組件的切換是在index中實現(xiàn))

在list頁面代碼

methods: {
    handleEdit() ·
      this.$router.push({
        query: {
          pagination: "edit",
          id: "0001",
        },
      }).catch(err =>{});e
    },
  },

使用this.$router.push()方法傳遞參數(shù)pagination(跳轉(zhuǎn)頁面)、id(其他參數(shù)),調(diào)用方法handleEdit在地址欄能看到傳的參數(shù)

image.png

在index頁面代碼

<template>
  <div>
    <component v-bind:is="currentTabComponent"></component>
  </div>
</template>
<script>
import edit from "./edit";
import list from "./list";
export default {
  data() {
    return {
      currentTabComponent: list,
    };
  },
  watch: {
    $route(route) {
      this.handlerouter();
    },
  },
  created() {
    this.handlerouter();
  },
  components: {
    edit,
    list,
  },
  methods: {
    handlerouter() {
      const { query } = this.$route;
      const { pagination, id } = query;
      if (!pagination) return this.currentTabComponent = list;
      switch (pagination) {
        case "edit":
          this.currentTabComponent = edit;
          break;
        default:
          this.currentTabComponent = list;
      }
    },
  },
};
</script>

handlerouter()方法中,通過es6語法取得參數(shù)pagination、id,判斷pagination不存在或為空時組件為list頁面并跳出方法,有pagination時,通過switch判斷來切換組件。

通過watch監(jiān)聽器來監(jiān)聽$route()方法=》監(jiān)聽路由,當list調(diào)用handleEdit()發(fā)生路由跳轉(zhuǎn),就會被監(jiān)聽到,執(zhí)行this.handlerouter()方法。

當在edit頁面進行瀏覽器刷新,參數(shù)pagination、id并不會被銷毀,但頁面刷新后會重新渲染執(zhí)行created()方法,在其中調(diào)用 this.handlerouter(),便能實現(xiàn)頁面頁面刷新后還是edit頁面了。

點個贊再走吧!!!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。