首页 > 解决方案 > 将 vuex PersistedState 与 vuex 模块一起使用

问题描述

我想将 PersistedState https://github.com/robinvdvleuten/vuex-persistedstate与 vuex 一起使用,但我无法正确设置。

我在商店目录中有这个模块

export const auth = {
  namespaced: true,
  state: {
  },
  getters: {
    countLinks: state => {
      return state.links.length
    }
  },
   mutations: {
    SET_LINKS: (state, links) => { 
      state.links = links;
    },
   //Synchronous
    ADD_LINK: (state, link) => {
      state.links.push(link)
    },
    REMOVE_LINK: (state, link) => {        
      state.links.splice(link, 1)
    },
    REMOVE_ALL: (state) => {                     
      state.links = []
    }
  },
  actions: {
  //Asynchronous
    removeLink: (context, link) => {
      context.commit("REMOVE_LINK", link)
    },
    removeAll ({commit}) {                       
      return new Promise((resolve) => {
        setTimeout(() => {
          commit('REMOVE_ALL')
          resolve()
        }, 1500)
      })
    }
  }
}

我已经命名了这个àuth.js

这是我的index.js文件也在商店目录中

import { createStore } from 'vuex'
import createPersistedState from "vuex-persistedstate"
import { auth } from './auth'


const dataState = createPersistedState({
  paths: ['data']
})

const store = createStore({
  modules: {
    auth
  },
  plugins: [dataState]
})

我总共有 7 个模块,我想在我的应用程序的各个地方加载和使用。要开始我只想加载身份验证模块并在我的home.vue页面中使用它

这是我 home.vue 的脚本部分

import Footer from '@/components/Footer.vue'
import Header from '@/components/Header.vue'
import { mapGetters} from 'vuex'
import store from '../store';



export default {
  name: 'Home',
  components: {
     Footer,Header
  },
  mounted () {
  var links  = ['http://google.com','http://coursetro.com','http://youtube.com'];
  store.commit('SET_LINKS', links);
},
  computed: {
    ...mapGetters([
      'countLinks'
    ]),
  }
}

这是我的 main.js 文件

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import i18n from './i18n'
import FlagIcon from 'vue-flag-icon'
import {store} from './store';


   
createApp(App).use(i18n).use(FlagIcon).use(store).use(router).mount('#app')

当我 npm run serve 时,我得到了错误

10:7 错误“存储”被分配了一个值,但从未使用过 no-unused-vars

我应该如何纠正这个问题才能在我的应用程序的任何地方使用 auth.js 模块?

标签: vue.jsvuexvuex-modules

解决方案


推荐阅读