5-5 使用vuex實現切換tab頁功能


目錄:

  •  實現Tab頁面功能
  • 實現步驟

一、實現Tab頁面功能

二、實現步驟

目錄結構:

...
-src
    -common   
        -Aside.vue 
        -Header.vue
        -Tab.vue   //定義Tab.vue
    -store
        -modules
            -tab.js   //定義tabsList
        -index.js
    -views     
        -Main.vue  //導入Tab.vue
    -App.vue
    -main.js
    -routes.js
....

步驟詳情:

  • 在 Main.vue中引入 Tab.vue組件(引用element-ui中的 tag標簽
  • 在 Vuex中定義存儲標簽的 tagList,方便非父子傳遞數據
  • 定義  vuex 中側邊欄 點擊后將菜單加入到 tagList中的方法
  • 定義 vuex 中點擊標簽后觸發刪除的方法

2.1、創建Tab.vue組件,並且在Main.vue中引入

創建Tab.vue組件:

<template>
  <div class="tabs">
      <!--大小 size='small'--> <!--v-for遍歷tags-->  <!--首頁不能刪除 :closable="tag.name !== 'home'"-->
      <el-tag :key="tag.name" size="small" v-for="tag in tags" :closable="tag.name !== 'home'" :disable-transitions="false" @close="handleClose(tag)">
        {{tag.label}}
      </el-tag>
  </div>

</template>

<script>
  import { mapState, mapMutations }   from 'vuex'    //引入vuex中的mapState,mapMutations
  export default {
    computed:{
      ...mapState({  //獲取tabsList,在module中,則獲取 state.tab.tabsList
        tags: state => state.tab.tabsList
      })
    },
    data() {
      return {
        dynamicTags: ['標簽一', '標簽二', '標簽三'],
        inputVisible: false,
        inputValue: ''
      };
    },
    methods: {
      ...mapMutations({   //調用vuex中的close方法
        close: 'closeTab'
      }),
      handleClose(tag) {
        this.close(tag)
      }
    }
  }
</script>

<style scoped>
  .tabs {   /*調整tabs樣式*/
    padding: 20px;
  }
  .tabs .el-tag {
    margin-right: 15px;
  }
</style>
Tab.vue

在 Main.vue 中導入

<template>
    <el-container style="height: 100%">
      .....
        <Tab></Tab>
        <el-main>Main</el-main>
      .....
</template>

<script>
  ....
  import Tab from '../common/Tab.vue'
  export default {
    components:{
      ....,
      Tab
    }
  }
</script>

<style scoped>
  ....
</style>
Main.vue

2.2、在 Vuex中定義存儲標簽的 tagList

const state = {
  menu: [],
  currentMenu: null,
  tabsList: [
    {
      path: '/',
      name: 'home',
      label: '首頁',
      icon: 's-home'
    },
  ]
};

const mutations = {
  selectMenu(state,val){
    //val.name != 'home' ? state.currentMenu = val:state.currentMenu = null;
    if(val.name != 'home'){
      state.currentMenu = val;
      let result = state.tabsList.findIndex(item => item.name === val.name);
      result === -1 ? state.tabsList.push(val) : ''
    }else {
      state.currentMenu = null;
    }
  },
  closeTab(state,val){
    let result = state.tabsList.findIndex(item => item.name === val.name);
    state.tabsList.splice(result,1);
  }

};

const actions = {

};

export default {
  state,
  mutations,
  actions
}
tab.js

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM