提交 41cba750 编写于 作者: Z zc

feat: 修改vuex为pinia

修改vuex为pinia
上级 d53c13ec
...@@ -67,43 +67,59 @@ export default router ...@@ -67,43 +67,59 @@ export default router
- [路由的 hash 模式和 history 模式的区别](https://www.cnblogs.com/GGbondLearn/p/12239651.html) - [路由的 hash 模式和 history 模式的区别](https://www.cnblogs.com/GGbondLearn/p/12239651.html)
## vuex ## pinia
```shell ```shell
npm install vuex@next npm install pinia
``` ```
src 下创建 store/interface.ts src 下创建 store/index.ts
```typescript ```typescript
import {InjectionKey} from 'vue' import { createPinia } from "pinia";
import {createStore, Store} from 'vuex' const store = createPinia();
export { store };
```
## main.ts
export interface State { ```typescript
count: number import {createApp} from 'vue'
} import App from './App.vue'
import router from "./router";
import '@/styles/index.scss'
import { store } from "./store";
import ElementPlus from 'element-plus'
import 'element-plus/theme-chalk/index.css'
import locale from 'element-plus/lib/locale/lang/zh-cn'
import 'virtual:svg-icons-register';
export const key: InjectionKey<Store<State>> = Symbol()
// @see https://blog.csdn.net/qq_37213281/article/details/121422027
import * as ElIconModules from '@element-plus/icons'
import '@/permission'
export const store = createStore<State>({
state() {
return {
count: 0
}
},
mutations: {
increment(state: { count: number }) {
state.count++
}
}
})
```
**参考文档:** import Pagination from '@/components/Pagination/index.vue'
import {getDictItemsByCode} from '@/api/system/dict'
const app = createApp(App)
- [Vue3 的 InjectionKey 解决提供者和消费者同步注入值的类型](https://www.jianshu.com/p/7064c5f8f143) // 统一注册el-icon图标
// @link https://blog.csdn.net/Alloom/article/details/119415984
for (let iconName in ElIconModules) {
app.component(iconName, (ElIconModules as any)[iconName])
}
// 全局方法
app.config.globalProperties.$getDictItemsByCode = getDictItemsByCode
app.component('Pagination', Pagination) // 全局组件
.use(store)
.use(router)
.use(ElementPlus, {locale})
.mount('#app')
```
## element-plus ## element-plus
......
...@@ -13,15 +13,13 @@ ...@@ -13,15 +13,13 @@
<script lang="ts"> <script lang="ts">
import {defineComponent} from "vue"; import {defineComponent} from "vue";
import {useStore} from '@/store'
import {useRoute} from "vue-router"; import {useRoute} from "vue-router";
import {tagsViewStoreHook} from '@/store/modules/tagsView'
export default defineComponent({ export default defineComponent({
setup() { setup() {
const store = useStore()
const route = useRoute() const route = useRoute()
const cachedViews = () => { const cachedViews = () => {
return store.state.tagsView.cachedViews return tagsViewStoreHook().cachedViews
} }
const key = () => { const key = () => {
return route.path return route.path
...@@ -68,4 +66,4 @@ export default defineComponent({ ...@@ -68,4 +66,4 @@ export default defineComponent({
padding-right: 15px; padding-right: 15px;
} }
} }
</style> </style>
\ No newline at end of file
...@@ -48,12 +48,13 @@ ...@@ -48,12 +48,13 @@
</template> </template>
<script> <script>
import {reactive, computed, toRefs} from "vue"; import {reactive, computed, toRefs} from "vue";
import {useStore} from "@/store";
import {useRoute, useRouter} from "vue-router" import {useRoute, useRouter} from "vue-router"
import Breadcrumb from '@/components/Breadcrumb/index.vue' import Breadcrumb from '@/components/Breadcrumb/index.vue'
import Hamburger from '@/components/Hamburger/index.vue' import Hamburger from '@/components/Hamburger/index.vue'
import Screenfull from '@/components/screenfull/index.vue' import Screenfull from '@/components/screenfull/index.vue'
import {tagsViewStoreHook} from '@/store/modules/tagsView'
import {useAppStoreHook} from '@/store/modules/app'
import {useUserStoreHook} from '@/store/modules/user'
export default { export default {
components: { components: {
Breadcrumb, Breadcrumb,
...@@ -61,26 +62,25 @@ export default { ...@@ -61,26 +62,25 @@ export default {
Screenfull Screenfull
}, },
setup() { setup() {
const store = useStore()
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const sidebar = computed(() => { const sidebar = computed(() => {
return store.state.app.sidebar return useAppStoreHook().sidebar
}) })
const device = computed(() => { const device = computed(() => {
return store.state.app.device return useAppStoreHook().device
}) })
const avatar = computed(() => { const avatar = computed(() => {
return store.state.user.avatar return useUserStoreHook().avatar
}) })
const state = reactive({ const state = reactive({
toggleSideBar: () => { toggleSideBar: () => {
store.dispatch('app/toggleSideBar', false) useAppStoreHook().toggleSidebar(false)
}, },
logout: () => { logout: () => {
store.dispatch('user/logout').then(()=>{ useUserStoreHook().logout().then(()=>{
router.push(`/login?redirect=${route.fullPath}`) router.push(`/login?redirect=${route.fullPath}`)
}) })
} }
......
...@@ -29,30 +29,30 @@ ...@@ -29,30 +29,30 @@
<script> <script>
import ThemePicker from '@/components/ThemePicker/index.vue' import ThemePicker from '@/components/ThemePicker/index.vue'
import {defineComponent, reactive, toRefs, watch} from "vue" import {defineComponent, reactive, toRefs, watch} from "vue"
import {useStore} from '@/store' // import {useStore} from '@/store'
import { useSettingStoreHook } from "@/store/modules/settings";
export default defineComponent({ export default defineComponent({
components: {ThemePicker}, components: {ThemePicker},
setup() { setup() {
const store = useStore() // const store = useStore()
const state = reactive({ const state = reactive({
fixedHeader:store.state.settings.fixedHeader, fixedHeader:useSettingStoreHook().fixedHeader,
tagsView:store.state.settings.tagsView, tagsView:useSettingStoreHook().tagsView,
sidebarLogo:store.state.settings.sidebarLogo, sidebarLogo:useSettingStoreHook().sidebarLogo,
themeChange: (val) => { themeChange: (val) => {
store.dispatch('settings/changeSetting', { key: 'theme', val }) useSettingStoreHook().changeSetting( { key: 'theme', val })
} }
}) })
watch(()=>state.fixedHeader,(value)=>{ watch(()=>state.fixedHeader,(value)=>{
store.dispatch('settings/changeSetting',{ key: 'fixedHeader', value }) useSettingStoreHook().changeSetting( { key: 'fixedHeader', value })
}) })
watch(() => state.tagsView, (value) => { watch(() => state.tagsView, (value) => {
store.dispatch('settings/changeSetting', { key: 'showTagsView', value }) useSettingStoreHook().changeSetting( { key: 'showTagsView', value })
}) })
watch(() => state.sidebarLogo, (value) => { watch(() => state.sidebarLogo, (value) => {
store.dispatch('settings/changeSetting', { key: 'sidebarLogo', value }) useSettingStoreHook().changeSetting( { key: 'sidebarLogo', value })
}) })
return { return {
......
...@@ -34,7 +34,9 @@ import {computed, defineComponent} from "vue"; ...@@ -34,7 +34,9 @@ import {computed, defineComponent} from "vue";
import SidebarItem from './SidebarItem.vue' import SidebarItem from './SidebarItem.vue'
import Logo from './Logo.vue' import Logo from './Logo.vue'
import variables from '@/styles/variables.scss' import variables from '@/styles/variables.scss'
import {useStore} from '@/store' import { useSettingStoreHook } from "@/store/modules/settings";
import { useAppStoreHook } from "@/store/modules/app";
import { usePermissionStoreHook } from "@/store/modules/permission";
import {useRoute} from 'vue-router' import {useRoute} from 'vue-router'
export default defineComponent({ export default defineComponent({
...@@ -43,11 +45,10 @@ export default defineComponent({ ...@@ -43,11 +45,10 @@ export default defineComponent({
Logo Logo
}, },
setup() { setup() {
const store = useStore();
const route = useRoute() const route = useRoute()
const sidebar = computed(() => store.state.app.sidebar) const sidebar = computed(() => useAppStoreHook().sidebar)
const routes = computed(() => store.state.permission.routes) const routes = computed(() => usePermissionStoreHook().routes)
const showLogo = computed(() => store.state.settings.sidebarLogo) const showLogo = computed(() => useSettingStoreHook().sidebarLogo)
const activeMenu = computed(() => { const activeMenu = computed(() => {
const {meta, path} = route const {meta, path} = route
// if set path, the sidebar will highlight the path you set // if set path, the sidebar will highlight the path you set
...@@ -56,7 +57,7 @@ export default defineComponent({ ...@@ -56,7 +57,7 @@ export default defineComponent({
} }
return path return path
}) })
const isCollapse = computed(() => !store.state.app.sidebar.opened) const isCollapse = computed(() => !useAppStoreHook().sidebar.opened)
return { return {
sidebar, sidebar,
......
...@@ -32,10 +32,10 @@ ...@@ -32,10 +32,10 @@
<script lang="ts"> <script lang="ts">
import {Close} from '@element-plus/icons' import {Close} from '@element-plus/icons'
import {tagsViewStoreHook} from '@/store/modules/tagsView'
import {usePermissionStoreHook} from '@/store/modules/Permission'
import ScrollPane from './ScrollPane.vue' import ScrollPane from './ScrollPane.vue'
import path from 'path-browserify' import path from 'path-browserify'
import {useStore} from "@store";
import { import {
defineComponent, defineComponent,
computed, computed,
...@@ -53,7 +53,6 @@ import {TagView} from "@store/interface"; ...@@ -53,7 +53,6 @@ import {TagView} from "@store/interface";
export default defineComponent({ export default defineComponent({
components: {ScrollPane,Close}, components: {ScrollPane,Close},
setup() { setup() {
const store = useStore()
const router = useRouter() const router = useRouter()
const instance = getCurrentInstance() const instance = getCurrentInstance()
const currentRoute = useRoute() const currentRoute = useRoute()
...@@ -86,7 +85,7 @@ export default defineComponent({ ...@@ -86,7 +85,7 @@ export default defineComponent({
return tag.meta && tag.meta.affix return tag.meta && tag.meta.affix
}, },
refreshSelectedTag: (view: TagView) => { refreshSelectedTag: (view: TagView) => {
store.dispatch('tagsView/delCachedView', view) tagsViewStoreHook().delCachedView(view)
const { fullPath } = view const { fullPath } = view
nextTick(() => { nextTick(() => {
router.replace({ path: '/redirect' + fullPath }).catch(err => { router.replace({ path: '/redirect' + fullPath }).catch(err => {
...@@ -95,23 +94,24 @@ export default defineComponent({ ...@@ -95,23 +94,24 @@ export default defineComponent({
}) })
}, },
closeSelectedTag: (view: TagView) => { closeSelectedTag: (view: TagView) => {
store.dispatch('tagsView/delView', view) tagsViewStoreHook().delView(view);
if (state.isActive(view)) { if (state.isActive(view)) {
toLastView(store.state.tagsView.visitedViews, view)
toLastView(tagsViewStoreHook().visitedViews, view)
} }
}, },
closeOthersTags: () => { closeOthersTags: () => {
if (state.selectedTag.fullPath !== currentRoute.path && state.selectedTag.fullPath !== undefined) { if (state.selectedTag.fullPath !== currentRoute.path && state.selectedTag.fullPath !== undefined) {
router.push(state.selectedTag.fullPath) router.push(state.selectedTag.fullPath)
} }
store.dispatch('tagsView/delOthersViews', state.selectedTag as TagView) tagsViewStoreHook().delOthersViews(state.selectedTag as TagView)
}, },
closeAllTags: (view: TagView) => { closeAllTags: (view: TagView) => {
store.dispatch('tagsView/delAllViews', undefined) tagsViewStoreHook().delAllViews(undefined);
if (state.affixTags.some(tag => tag.path === currentRoute.path)) { if (state.affixTags.some(tag => tag.path === currentRoute.path)) {
return return
} }
toLastView(store.state.tagsView.visitedViews, view) toLastView(tagsViewStoreHook().visitedViews, view)
}, },
openMenu: (tag: TagView, e: MouseEvent) => { openMenu: (tag: TagView, e: MouseEvent) => {
const menuMinWidth = 105 const menuMinWidth = 105
...@@ -138,9 +138,9 @@ export default defineComponent({ ...@@ -138,9 +138,9 @@ export default defineComponent({
}) })
const visitedViews = computed(() => { const visitedViews = computed(() => {
return store.state.tagsView.visitedViews return tagsViewStoreHook().visitedViews
}) })
const routes = computed(() => store.state.permission.routes) const routes = computed(() =>usePermissionStoreHook().routes)
const filterAffixTags = (routes: RouteRecordRaw[], basePath = '/') => { const filterAffixTags = (routes: RouteRecordRaw[], basePath = '/') => {
let tags: TagView[] = [] let tags: TagView[] = []
...@@ -171,14 +171,14 @@ export default defineComponent({ ...@@ -171,14 +171,14 @@ export default defineComponent({
for (const tag of state.affixTags) { for (const tag of state.affixTags) {
// Must have tag name // Must have tag name
if (tag.name) { if (tag.name) {
store.dispatch('tagsView/addVisitedView', tag as TagView) tagsViewStoreHook().addVisitedView(tag as TagView)
} }
} }
} }
const addTags = () => { const addTags = () => {
if (currentRoute.name) { if (currentRoute.name) {
store.dispatch('tagsView/addView', currentRoute) tagsViewStoreHook().addView(currentRoute)
} }
return false return false
} }
...@@ -192,7 +192,7 @@ export default defineComponent({ ...@@ -192,7 +192,7 @@ export default defineComponent({
(scrollPaneRef.value as any).moveToCurrentTag(tag) (scrollPaneRef.value as any).moveToCurrentTag(tag)
// When query is different then update // When query is different then update
if ((tag.to as TagView).fullPath !== currentRoute.fullPath) { if ((tag.to as TagView).fullPath !== currentRoute.fullPath) {
store.dispatch('tagsView/updateVisitedView', currentRoute) tagsViewStoreHook().updateVisitedView(currentRoute)
} }
} }
} }
......
...@@ -21,9 +21,9 @@ ...@@ -21,9 +21,9 @@
<script> <script>
import {computed, defineComponent, onBeforeMount, onBeforeUnmount, onMounted, reactive, toRefs, watch} from "vue"; import {computed, defineComponent, onBeforeMount, onBeforeUnmount, onMounted, reactive, toRefs, watch} from "vue";
import {AppMain, Navbar, Settings, Sidebar, TagsView} from './components/index.ts' import {AppMain, Navbar, Settings, Sidebar, TagsView} from './components/index.ts'
import {useStore} from "@store"; import {useRoute} from "vue-router";
import {useRoute} from "vue-router"; import { useAppStoreHook } from "@/store/modules/app";
import { useSettingStoreHook } from "@/store/modules/settings";
const {body} = document const {body} = document
const WIDTH = 992 const WIDTH = 992
...@@ -37,9 +37,7 @@ export default defineComponent({ ...@@ -37,9 +37,7 @@ export default defineComponent({
TagsView TagsView
}, },
setup() { setup() {
const store = useStore() const sidebar = computed(() => useAppStoreHook().sidebar)
const sidebar = computed(() => store.state.app.sidebar)
const isMobile = () => { const isMobile = () => {
const rect = body.getBoundingClientRect() const rect = body.getBoundingClientRect()
return rect.width - 1 < WIDTH return rect.width - 1 < WIDTH
...@@ -47,17 +45,17 @@ export default defineComponent({ ...@@ -47,17 +45,17 @@ export default defineComponent({
const resizeHandler = () => { const resizeHandler = () => {
if (!document.hidden) { if (!document.hidden) {
store.dispatch('app/toggleDevice', isMobile() ? 'mobile' : 'desktop') useAppStoreHook().toggleSidebar( isMobile() ? 'mobile' : 'desktop')
if (isMobile()) { if (isMobile()) {
store.dispatch('app/closeSideBar', {withoutAnimation: true}) useAppStoreHook().closeSideBar({withoutAnimation: true});
} }
} }
} }
const resizeMounted = () => { const resizeMounted = () => {
if (isMobile()) { if (isMobile()) {
store.dispatch('app/toggleDevice', 'mobile') useAppStoreHook().toggleDevice( 'mobile' )
store.dispatch('app/closeSideBar', {withoutAnimation: true}) useAppStoreHook().toggleSidebar({withoutAnimation: true});
} }
} }
const addEventListenerOnResize = () => { const addEventListenerOnResize = () => {
...@@ -70,35 +68,35 @@ export default defineComponent({ ...@@ -70,35 +68,35 @@ export default defineComponent({
const currentRoute = useRoute() const currentRoute = useRoute()
const watchRouter = watch(() => currentRoute.name, () => { const watchRouter = watch(() => currentRoute.name, () => {
if (store.state.app.device === 'mobile' && store.state.app.sidebar.opened) { if (useAppStoreHook().device === 'mobile' && useAppStoreHook().sidebar.opened) {
store.dispatch('app/closeSideBar', false) useAppStoreHook().closeSideBar(false)
} }
}) })
const state = reactive({ const state = reactive({
handleClickOutside: () => { handleClickOutside: () => {
store.dispatch('app/closeSideBar', false) useAppStoreHook().closeSideBar(false)
} }
}) })
const classObj = computed(() => { const classObj = computed(() => {
return { return {
hideSidebar: !store.state.app.sidebar.opened, hideSidebar: !useAppStoreHook().sidebar.opened,
openSidebar: store.state.app.sidebar.opened, openSidebar: useAppStoreHook().sidebar.opened,
withoutAnimation: store.state.app.sidebar.withoutAnimation, withoutAnimation: useAppStoreHook().sidebar.withoutAnimation,
mobile: store.state.app.device === 'mobile' mobile: useAppStoreHook().device === 'mobile'
} }
}) })
const showSettings = computed(() => { const showSettings = computed(() => {
return store.state.settings.showSettings return useSettingStoreHook().showSettings
}) })
const needTagsView = computed(() => { const needTagsView = computed(() => {
return store.state.settings.tagsView return useSettingStoreHook().tagsView
}) })
const fixedHeader = computed(() => { const fixedHeader = computed(() => {
return store.state.settings.fixedHeader return useSettingStoreHook().fixedHeader
}) })
watchRouter() watchRouter()
......
import {createApp} from 'vue' import {createApp} from 'vue'
import App from './App.vue' import App from './App.vue'
import router from "./router"; import router from "./router";
// import {store, key} from './store'
import { setupStore } from "@/store";
import '@/styles/index.scss' import '@/styles/index.scss'
import { store } from "./store";
import ElementPlus from 'element-plus' import ElementPlus from 'element-plus'
import 'element-plus/theme-chalk/index.css' import 'element-plus/theme-chalk/index.css'
import locale from 'element-plus/lib/locale/lang/zh-cn' import locale from 'element-plus/lib/locale/lang/zh-cn'
...@@ -30,8 +28,8 @@ for (let iconName in ElIconModules) { ...@@ -30,8 +28,8 @@ for (let iconName in ElIconModules) {
// 全局方法 // 全局方法
app.config.globalProperties.$getDictItemsByCode = getDictItemsByCode app.config.globalProperties.$getDictItemsByCode = getDictItemsByCode
setupStore(app);
app.component('Pagination', Pagination) // 全局组件 app.component('Pagination', Pagination) // 全局组件
.use(store)
.use(router) .use(router)
.use(ElementPlus, {locale}) .use(ElementPlus, {locale})
.mount('#app') .mount('#app')
import type { App } from "vue";
import { createPinia } from "pinia"; import { createPinia } from "pinia";
const store = createPinia(); const store = createPinia();
export function setupStore(app: App<Element>) {
app.use(store);
}
export { store }; export { store };
// import {Module} from "vuex";
import {AppState} from "@store/interface"; import {AppState} from "@store/interface";
import {Local} from "@utils/storage"; import {Local} from "@utils/storage";
// import { storageLocal } from "/@/utils/storage";
import { store } from "@/store"; import { store } from "@/store";
// import { appType } from "./types";
import { defineStore } from "pinia"; import { defineStore } from "pinia";
// import { getConfig } from "/@/config";
export const useAppStore = defineStore({ export const useAppStore = defineStore({
id: "youlai-app", id: "youlai-app",
...@@ -18,34 +13,24 @@ export const useAppStore = defineStore({ ...@@ -18,34 +13,24 @@ export const useAppStore = defineStore({
} }
}), }),
actions: { actions: {
async TOGGLE_SIDEBAR(state:any) { toggleSidebar() {
state.sidebar.opened = !state.sidebar.opened this.sidebar.opened = !this.sidebar.opened
console.log('state.sidebar.opened',state.sidebar.opened) this.sidebar.withoutAnimation = false
state.sidebar.withoutAnimation = false if (this.sidebar.opened) {
if (state.sidebar.opened) {
Local.set('sidebarStatus', 1) Local.set('sidebarStatus', 1)
} else { } else {
Local.set('sidebarStatus', 0) Local.set('sidebarStatus', 0)
} }
}, },
async CLOSE_SIDEBAR (state:any, withoutAnimation:any) { closeSideBar ( withoutAnimation:any) {
Local.set('sidebarStatus', 0) Local.set('sidebarStatus', 0)
state.sidebar.opened = false this.sidebar.opened = false
state.sidebar.withoutAnimation = withoutAnimation this.sidebar.withoutAnimation = withoutAnimation
}, },
async TOGGLE_DEVICE(state:any, device:any) { toggleDevice( device:any) {
console.log('TOGGLE_DEVICE',device) console.log('TOGGLE_DEVICE',device)
state.device = device this.device = device
}, }
// toggleSideBar({commit}) {
// commit('TOGGLE_SIDEBAR')
// },
// closeSideBar({commit}, {withoutAnimation}) {
// commit('CLOSE_SIDEBAR', withoutAnimation)
// },
// async toggleDevice({commit}, device) {
// commit('TOGGLE_DEVICE', device)
// }
} }
}) })
export function useAppStoreHook() { export function useAppStoreHook() {
......
// import {Module} from "vuex"; import {PermissionState} from "@store/interface";
import {PermissionState, RootStateTypes} from "@store/interface";
import {RouteRecordRaw} from 'vue-router' import {RouteRecordRaw} from 'vue-router'
import {constantRoutes} from '@/router' import {constantRoutes} from '@/router'
import {listRoutes} from "@/api/system/menu"; import {listRoutes} from "@/api/system/menu";
...@@ -53,7 +52,7 @@ export const usePermissionStore = defineStore({ ...@@ -53,7 +52,7 @@ export const usePermissionStore = defineStore({
addRoutes: [] addRoutes: []
}), }),
actions: { actions: {
async SET_ROUTES( routes: RouteRecordRaw[]){ setRoutes( routes: RouteRecordRaw[]){
this.addRoutes = routes this.addRoutes = routes
this.routes = constantRoutes.concat(routes) this.routes = constantRoutes.concat(routes)
}, },
...@@ -67,7 +66,7 @@ export const usePermissionStore = defineStore({ ...@@ -67,7 +66,7 @@ export const usePermissionStore = defineStore({
} else { } else {
accessedRoutes = filterAsyncRoutes(asyncRoutes, roles) accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
} }
this.SET_ROUTES(accessedRoutes) this.setRoutes(accessedRoutes)
resolve(accessedRoutes) resolve(accessedRoutes)
}).catch(error => { }).catch(error => {
reject(error) reject(error)
......
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import { store } from "@/store"; import { store } from "@/store";
// import {Module} from "vuex"; import {SettingState} from "@store/interface";
import {SettingState, RootStateTypes} from "@store/interface";
import defaultSettings from '../../settings' import defaultSettings from '../../settings'
const {showSettings, tagsView, fixedHeader, sidebarLogo} = defaultSettings const {showSettings, tagsView, fixedHeader, sidebarLogo} = defaultSettings
...@@ -16,7 +15,7 @@ export const useSettingStore = defineStore({ ...@@ -16,7 +15,7 @@ export const useSettingStore = defineStore({
sidebarLogo: sidebarLogo, sidebarLogo: sidebarLogo,
}), }),
actions: { actions: {
async CHANGE_SETTING( payload: { key: string, value: any }){ async changeSetting( payload: { key: string, value: any }){
const {key, value} = payload const {key, value} = payload
switch (key) { switch (key) {
case 'theme': case 'theme':
...@@ -37,9 +36,6 @@ export const useSettingStore = defineStore({ ...@@ -37,9 +36,6 @@ export const useSettingStore = defineStore({
default: default:
break break
} }
},
changeSetting(data:any) {
this.CHANGE_SETTING(data)
} }
} }
}) })
......
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import { store } from "@/store"; import { store } from "@/store";
// import {Module} from "vuex"; import {TagsViewState} from "@store/interface";
import {TagsViewState,RootStateTypes} from "@store/interface";
const tagsViewStore=defineStore({ const tagsViewStore=defineStore({
id:"youlai-tagsView", id:"youlai-tagsView",
...@@ -11,7 +10,7 @@ const tagsViewStore=defineStore({ ...@@ -11,7 +10,7 @@ const tagsViewStore=defineStore({
cachedViews: [] cachedViews: []
}), }),
actions: { actions: {
async ADD_VISITED_VIEW ( view:any) { addVisitedView ( view:any) {
if (this.visitedViews.some(v => v.path === view.path)) return if (this.visitedViews.some(v => v.path === view.path)) return
this.visitedViews.push( this.visitedViews.push(
Object.assign({}, view, { Object.assign({}, view, {
...@@ -19,51 +18,58 @@ const tagsViewStore=defineStore({ ...@@ -19,51 +18,58 @@ const tagsViewStore=defineStore({
}) })
) )
}, },
async ADD_CACHED_VIEW(view:any) { addCachedView(view:any) {
if (this.cachedViews.includes(view.name)) return if (this.cachedViews.includes(view.name)) return
if (!view.meta.noCache) { if (!view.meta.noCache) {
this.cachedViews.push(view.name) this.cachedViews.push(view.name)
} }
}, },
async DEL_VISITED_VIEW( view:any) { delVisitedView( view:any) {
for (const [i, v] of this.visitedViews.entries()) { return new Promise(resolve => {
if (v.path === view.path) { for (const [i, v] of this.visitedViews.entries()) {
this.visitedViews.splice(i, 1) if (v.path === view.path) {
break this.visitedViews.splice(i, 1)
} break
} }
}, }
async DEL_CACHED_VIEW ( view:any) { resolve([...this.visitedViews])
const index = this.cachedViews.indexOf(view.name) })
index > -1 && this.cachedViews.splice(index, 1)
},
async DEL_OTHERS_VISITED_VIEWS (view:any) {
this.visitedViews = this.visitedViews.filter(v => {
return v.meta?.affix || v.path === view.path
})
}, },
async DEL_OTHERS_CACHED_VIEWS( view:any) { delCachedView ( view:any) {
const index = this.cachedViews.indexOf(view.name) return new Promise(resolve => {
if (index > -1) { const index = this.cachedViews.indexOf(view.name)
this.cachedViews = this.cachedViews.slice(index, index + 1) index > -1 && this.cachedViews.splice(index, 1)
} else { resolve([...this.cachedViews])
// if index = -1, there is no cached tags })
this.cachedViews = []
}
}, },
DEL_ALL_VISITED_VIEWS() { delOthersVisitedViews (view:any) {
// keep affix tags return new Promise(resolve => {
const affixTags = this.visitedViews.filter(tag => tag.meta?.affix) this.visitedViews = this.visitedViews.filter(v => {
this.visitedViews = affixTags return v.meta?.affix || v.path === view.path
})
resolve([...this.visitedViews])
})
}, },
DEL_ALL_CACHED_VIEWS() { delOthersCachedViews( view:any) {
this.cachedViews = [] return new Promise(resolve => {
const index = this.cachedViews.indexOf(view.name)
if (index > -1) {
this.cachedViews = this.cachedViews.slice(index, index + 1)
} else {
// if index = -1, there is no cached tags
this.cachedViews = []
}
resolve([...this.cachedViews])
})
}, },
UPDATE_VISITED_VIEW (view:any) { updateVisitedView (view:any) {
for (let v of this.visitedViews) { for (let v of this.visitedViews) {
if (v.path === view.path) { if (v.path === view.path) {
v = Object.assign(v, view) v = Object.assign(v, view)
...@@ -72,15 +78,9 @@ const tagsViewStore=defineStore({ ...@@ -72,15 +78,9 @@ const tagsViewStore=defineStore({
} }
}, },
addView( view:any) { addView( view:any) {
this.addVisitedView( view) this.addVisitedView( view)
this.addCachedView(view) this.addCachedView(view)
}, },
addVisitedView( view:any) {
this.ADD_VISITED_VIEW( view)
},
addCachedView( view:any) {
this.ADD_CACHED_VIEW(view)
},
delView( view:any) { delView( view:any) {
return new Promise(resolve => { return new Promise(resolve => {
this.delVisitedView(view) this.delVisitedView(view)
...@@ -91,18 +91,6 @@ const tagsViewStore=defineStore({ ...@@ -91,18 +91,6 @@ const tagsViewStore=defineStore({
}) })
}) })
}, },
delVisitedView( view:any) {
return new Promise(resolve => {
this.DEL_VISITED_VIEW( view)
resolve([...this.visitedViews])
})
},
delCachedView( view:any) {
return new Promise(resolve => {
this.DEL_CACHED_VIEW(view)
resolve([...this.cachedViews])
})
},
delOthersViews( view:any) { delOthersViews( view:any) {
return new Promise(resolve => { return new Promise(resolve => {
this.delOthersVisitedViews(view) this.delOthersVisitedViews(view)
...@@ -113,23 +101,11 @@ const tagsViewStore=defineStore({ ...@@ -113,23 +101,11 @@ const tagsViewStore=defineStore({
}) })
}) })
}, },
delOthersVisitedViews( view:any) {
return new Promise(resolve => {
this.DEL_OTHERS_VISITED_VIEWS(view)
resolve([...this.visitedViews])
})
},
delOthersCachedViews( view:any) {
return new Promise(resolve => {
this.DEL_OTHERS_CACHED_VIEWS(view)
resolve([...this.cachedViews])
})
},
delAllViews( view:any) { delAllViews( view:any) {
return new Promise(resolve => { return new Promise(resolve => {
this.delAllVisitedViews() const affixTags = this.visitedViews.filter(tag => tag.meta?.affix)
this.delAllCachedViews() this.visitedViews = affixTags
this.cachedViews = []
resolve({ resolve({
visitedViews: [...this.visitedViews], visitedViews: [...this.visitedViews],
cachedViews: [...this.cachedViews] cachedViews: [...this.cachedViews]
...@@ -138,19 +114,17 @@ const tagsViewStore=defineStore({ ...@@ -138,19 +114,17 @@ const tagsViewStore=defineStore({
}, },
delAllVisitedViews() { delAllVisitedViews() {
return new Promise(resolve => { return new Promise(resolve => {
this.DEL_ALL_VISITED_VIEWS const affixTags = this.visitedViews.filter(tag => tag.meta?.affix)
this.visitedViews = affixTags
resolve([...this.visitedViews]) resolve([...this.visitedViews])
}) })
}, },
delAllCachedViews() { delAllCachedViews() {
return new Promise(resolve => { return new Promise(resolve => {
this.DEL_ALL_CACHED_VIEWS this.cachedViews = []
resolve([...this.cachedViews]) resolve([...this.cachedViews])
}) })
}, },
updateVisitedView( view:any) {
this.UPDATE_VISITED_VIEW(view)
}
} }
}) })
......
...@@ -27,24 +27,8 @@ export const useUserStore = defineStore({ ...@@ -27,24 +27,8 @@ export const useUserStore = defineStore({
}), }),
actions: { actions: {
async RESET_STATE () { async RESET_STATE () {
// Object.assign(this.state, getDefaultState())
this.$reset() this.$reset()
}, },
async SET_TOKEN(token: string) {
this.token = token
},
async SET_NICKNAME( nickname: string) {
this.nickname = nickname
},
async SET_AVATAR(avatar: string) {
this.avatar = avatar
},
async SET_ROLES(roles: string[]) {
this.roles = roles
},
async SET_PERMS( perms: string[]) {
this.perms = perms
},
/** /**
* 用户登录请求 * 用户登录请求
* @param userInfo 登录用户信息 * @param userInfo 登录用户信息
...@@ -68,7 +52,7 @@ export const useUserStore = defineStore({ ...@@ -68,7 +52,7 @@ export const useUserStore = defineStore({
const {access_token, token_type} = response.data const {access_token, token_type} = response.data
const accessToken = token_type + " " + access_token const accessToken = token_type + " " + access_token
Local.set("token", accessToken) Local.set("token", accessToken)
this.SET_TOKEN(accessToken) this.token = accessToken
resolve(access_token) resolve(access_token)
}).catch(error => { }).catch(error => {
reject(error) reject(error)
...@@ -85,16 +69,14 @@ export const useUserStore = defineStore({ ...@@ -85,16 +69,14 @@ export const useUserStore = defineStore({
if (!data) { if (!data) {
return reject('Verification failed, please Login again.') return reject('Verification failed, please Login again.')
} }
console.log(data)
const {nickname, avatar, roles, perms} = data const {nickname, avatar, roles, perms} = data
if (!roles || roles.length <= 0) { if (!roles || roles.length <= 0) {
reject('getUserInfo: roles must be a non-null array!') reject('getUserInfo: roles must be a non-null array!')
} }
this.SET_NICKNAME(nickname) this.nickname = nickname
this.SET_AVATAR( avatar) this.avatar = avatar
this.SET_ROLES( roles) this.roles = roles
this.SET_PERMS( perms) this.perms = perms
resolve(data) resolve(data)
}).catch(error => { }).catch(error => {
reject(error) reject(error)
......
import axios from "axios"; import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus"; import {ElMessage, ElMessageBox} from "element-plus";
import {Local} from "@utils/storage"; import {Local} from "@utils/storage";
import {store} from "@store"; import { useUserStoreHook } from "@/store/modules/user";
// 创建 axios 实例 // 创建 axios 实例
const service = axios.create({ const service = axios.create({
...@@ -17,7 +16,7 @@ service.interceptors.request.use( ...@@ -17,7 +16,7 @@ service.interceptors.request.use(
if (!config?.headers) { if (!config?.headers) {
throw new Error(`Expected 'config' and 'config.headers' not to be undefined`); throw new Error(`Expected 'config' and 'config.headers' not to be undefined`);
} }
if (store.state.user.token) { if (useUserStoreHook().token) {
config.headers.Authorization = `${Local.get('token')}`; config.headers.Authorization = `${Local.get('token')}`;
} }
return config return config
...@@ -62,4 +61,4 @@ service.interceptors.response.use( ...@@ -62,4 +61,4 @@ service.interceptors.response.use(
); );
// 导出 axios 实例 // 导出 axios 实例
export default service export default service
\ No newline at end of file
...@@ -72,7 +72,7 @@ ...@@ -72,7 +72,7 @@
<script> <script>
import SvgIcon from '@/components/SvgIcon/index.vue'; import SvgIcon from '@/components/SvgIcon/index.vue';
import {getCaptcha} from "@/api/login"; import {getCaptcha} from "@/api/login";
import { useUserStoreHook } from "@/store/modules/user";
export default { export default {
name: 'Login', name: 'Login',
components:{ components:{
...@@ -130,7 +130,7 @@ export default { ...@@ -130,7 +130,7 @@ export default {
this.$refs.loginForm.validate(valid => { this.$refs.loginForm.validate(valid => {
if (valid) { if (valid) {
this.loading = true this.loading = true
this.$store.dispatch('user/login', this.loginForm).then(() => { useUserStoreHook().login(this.loginForm).then(() => {
this.$router.push({ path: this.redirect || '/' }) this.$router.push({ path: this.redirect || '/' })
this.loading = false this.loading = false
}).catch(() => { }).catch(() => {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册