vue3使用vuex的getters

vue3使用vuex的getters_第1张图片
// index.js

import { createStore } from 'vuex'
import VuexPersistence from 'vuex-persist'

import  router  from './module/router'
import user  from './module/user'

const vuexLocal = new VuexPersistence({
    storage: window.localStorage,
})

export const store = createStore({
    modules: {
        router,
        user,
    },
    plugins: [vuexLocal.plugin]
})

// user.js

import { login } from '@/api/test'
import  router  from '@/router'
export default {
    namespaced: true,
    state: {
        token:""
    },
    mutations: {
        setToken(state, value) {
            state.token = value
        },
    },
    actions: {
        async setUserInfo({ commit }, value) {
            const res = await login()
            if(res.code==200){
                commit('setToken',res.data.token)
            }
        },
    },
    getters: {
        getToken(state) {
          return state.token
        }
    }
}

// 路由守卫

import router from "@/router"
import { store } from '../store/index'
import useStore from '../store/module/user.js'

console.log(useStore.getters.getToken()); // 报错
// 获取不到vuex.store.token;

// 路由守卫
router.beforeEach((to, form, next) => {
  if(to.path!=='/login'){
    let state={
      token:'123'
    }
      console.log(store.getters['user/getToken']); // 拿到(必须是动态赋值,默认值拿不到)
      
      console.log(useStore.getters.getToken(state)); // 123
      // 获取到当前页面的state
      next()
  }else{
      next()
  }
});

你可能感兴趣的:(vue,javascript,前端,vue.js,vue3,vue)