Commit c0e122b5 by wusiyi

fix: 保持首页在第一位

parent d8fb0797
const lastSavedTags = localStorage.getItem('tags') ? JSON.parse(localStorage.getItem('tags')) || [] : [] const HOME_TAG = { name: 'home', path: '/saas/home', title: '首页', id: 1 }
let tagId = lastSavedTags.reduce( const lastSavedTags = localStorage.getItem('tags')
(a, c) => Math.max(a, c.id), ? JSON.parse(localStorage.getItem('tags')) || []
0, : []
) let tagId = lastSavedTags.reduce((a, c) => Math.max(a, c.id), 0)
// 确保首页始终在第一位
function ensureHomeFirst(tags) {
const filtered = tags.filter((t) => t.name !== 'home')
return [HOME_TAG, ...filtered]
}
console.log(lastSavedTags) console.log(lastSavedTags)
/** /**
* @type {import('vuex').StoreOptions} * @type {import('vuex').StoreOptions}
...@@ -10,32 +15,29 @@ console.log(lastSavedTags) ...@@ -10,32 +15,29 @@ console.log(lastSavedTags)
const tags = { const tags = {
namespaced: true, namespaced: true,
state: { state: {
tags: lastSavedTags || [], tags: ensureHomeFirst(lastSavedTags),
activeTag: undefined, activeTag: undefined
}, },
getters: { getters: {
currentTag(state) { currentTag(state) {
return state.tags.find( return state.tags.find((e) => e.name === state.activeTag)
(e) => e.name === state.activeTag, }
)
},
}, },
mutations: { mutations: {
add(state, tag) { add(state, tag) {
// 禁止添加重复首页tag
if (tag.name === 'home') return HOME_TAG.id
const item = { const item = {
...tag, ...tag,
id: ++tagId, id: ++tagId
} }
const index = state.tags.findIndex( const index = state.tags.findIndex((t) => t.name === tag.name)
(t) => t.name === tag.name,
)
if (index === -1) { if (index === -1) {
state.tags.push(item) state.tags.push(item)
} }
localStorage.setItem( // 始终保证首页在第一位
'tags', state.tags = ensureHomeFirst(state.tags)
JSON.stringify(state.tags), localStorage.setItem('tags', JSON.stringify(state.tags))
)
return item.id return item.id
}, },
setActive(state, name) { setActive(state, name) {
...@@ -43,9 +45,9 @@ const tags = { ...@@ -43,9 +45,9 @@ const tags = {
state.activeTag = name state.activeTag = name
}, },
remove(state, name) { remove(state, name) {
const index = state.tags.findIndex( // 禁止移除首页tag
(e) => e.name === name, if (name === 'home') return
) const index = state.tags.findIndex((e) => e.name === name)
if (index === -1) return if (index === -1) return
state.tags.splice(index, 1) state.tags.splice(index, 1)
...@@ -60,15 +62,12 @@ const tags = { ...@@ -60,15 +62,12 @@ const tags = {
} }
} }
localStorage.setItem( localStorage.setItem('tags', JSON.stringify(state.tags))
'tags',
JSON.stringify(state.tags),
)
}, },
removeAllTags(state) { removeAllTags(state) {
state.tags = [] state.tags = []
}, }
}, }
} }
export default tags export default tags
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment