vue+element實現頁面頂部tag思路詳解
阿新 • • 發佈:2021-12-30
目錄
- 1. 頁面渲染
- 2. 來回切換tag
- 3. 刪除一個tag標籤
這種tag如何寫?思路總結下:
1. 頁面渲染
1頁面顯示由陣列迴圈得出,陣列可儲存在shttp://www.cppcns.comtore裡
(1)儲存前判斷是否有重複的資料,重複的話,先刪除再新增。
(2)沒有重複直接push
addTag: (state,tag) => { const { fullPath,path,meta,query } = tag if (tag.path === '/login') { return false } const findIndex = state.tags.findIndex(item => item.path === tag.path) console.log(findIndex) if (findIndex >= 0) { state.tags.splice(findIndex,1,{ fullPath,query }) } else { state.tags.push({ fullPath,query }) } },
2何時觸發這個新增路由方法,監聽路由進入的時候,調此方法將當前this例項上的route物件攜帶過去。
computed: { currentRoute() { return this.$route },},watch: { $route: { handler(val) { if (val.name) { this.addTags() } },// 深度觀察監聽 deep: true } },methods:{ addTags() { //this.$store.dispatch 先提交給action,由他非同步處理處罰mutation裡面的方法,改變state裡面的tags值 this.$store.dispatch('user/addTag',this.currentRoute) },}
此時,tags數組裡面已經有值,由於預設是白色,所以頁面上看不出,接下來就是給選中的標籤高亮。
1element 有個引數可以設定,可以查文件。
2選中的tag值是否等於當前路由進入的頁面一致,一致則為true。
<span v-for="(tag,index) in tags" :key="index" class="tag-span"> <el-tag :closable="isCloseable" :effect="setTagColor(tag)" @close="closeTags(tag)" @click="toTagRoute(tag)" > {{ tag.meta.title }} </el-tag> </span> methods:{ setTagColor(tag) { return this.currentRoute.path === tag.path ? 'dark' : 'plain' },}
此時,tag的渲染和選中就完成了。
2. 來回切換tag
methods:{ http://www.cppcns.comtoTagRoute(tag) { this.$router.push({ path: tag.fullPath || tag.path }) SSCZWDeqav },}
3. 刪除一個tag標籤
1由於是陣列,你無法確定使用者刪除哪一個,所以需要遍歷找出使用者當前選中的tag。然後刪除,同時更新store裡的值。
2刪除當前tag,高亮的標籤是哪一個?這裡是刪除標籤的前一個標籤,也就是陣列最後一個元素。
methods:{ closeTags(tag) { console.log(tag,4444) this.$store.dispatch('user/delTag',tag) this.toLastTagRouter(this.$store.state.user.tags)//高亮刪除標籤的前一個tag },toLastTagRouter(tags) { //注意此處傳入tags是已刪除後的,所以不能使用splice==》改變原陣列;slice==》不改變原陣列拿去陣列最後一個元素 const latestView = tags.slice(-1)[0]//tags陣列最後一個元素 console.log(latestView) if (latestView !== undefined && latestView.path !== undefined) { const { fullPath,query } = latestView this.$router.push({ fullPath,query }) } },} //action delTag({ commit },tag) { commit('delTag',tag) },//mutation delTag: (state,tag) => { //entries()物件變成一個可遍歷的陣列【0,{name:a,age:'20'}】 //這裡使用forEach和map也可以 for (const [i,v] of state.tags.entries()) { if (v.path === tag.path) { state.tags.splice(i,1) break } } },
刪除全部標籤
methods:{
closeAllTags() {
// 關閉所有 tag,僅剩餘一個
this.$store.dispatch('user/delAllTags')
const { fullPath,query } = this.$store.stawww.cppcns.comte.user.tags[0]
// 跳轉剩餘 tag 路由
this.$router.push({ fullPath,query })
},}
//action
delAllTags({ commit }) {
commit('delAllTags')
},//mutation
delAllTags: (state) => {
state.tags.splice(1,state.tags.length)
},
到此這篇關於+element如何實現頁面頂部tag的文章就介紹到這了,更多相關vue element頁面頂部tag內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!