【问题标题】:Use vuex state in Vuetify.js plugin在 Vuetify.js 插件中使用 vuex 状态
【发布时间】:2020-10-23 22:02:29
【问题描述】:

我对在 Vuetify.js 插件中调用 vuex 状态感到非常困惑。

我的项目是根据用户的首选语言翻译网站。我已经用 i18n 完全设置了翻译。该项目由两部分组成。

  1. 基于 JSON 文件的翻译(效果很好)
  2. Vuetify 组件的翻译基于 Vuetify 提供的翻译。

第二点是我卡住的地方。 根据 Vuetify 的手册,您需要在 Vuetify.js 插件中导入所需的语言文件。这一切都很完美。

但是……我只能手动更改……

我想要实现的是根据我的 vuex 商店中设置的语言设置正确的 Vuetify 语言。 相信我,我已经在互联网上搜索了好几天,并尝试了所有我能找到的东西。但似乎没有任何效果。我似乎无法弄清楚如何在 Vuetify.js 插件中调用 vuex 状态。

import Vue from 'vue'
import Vuetify from 'vuetify/lib'

Vue.use(Vuetify)

import nl from 'vuetify/es5/locale/nl'
import fr from 'vuetify/es5/locale/fr'
import en from 'vuetify/es5/locale/en'

Vue.component('my-component', {
 methods: {
    changeLocale() {
        this.$vuetify.lang.current
    },
 },
})
export default new Vuetify({
 lang: {
    locales: { nl, en, fr },
    current: "nl",
},
})

所以current的状态应该以我的vuex store中的状态为准。

这是我的 vuex 商店

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import i18n, { selectedLocale } from './i18n'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    locale: selectedLocale
  },
  mutations: {
    updateLocale(state, newLocale) {
      state.locale = newLocale
    }
  },
  actions: {
    changeLocale({ commit }, newLocale) {
      i18n.locale = newLocale
      commit('updateLocale', newLocale)
    }
  },
  plugins: [createPersistedState()]
})

谁能正确地告诉我该由谁去做?

【问题讨论】:

  • 有一个例子如何将 Vue-i18n 与 Vuetify 集成 - vuetifyjs.com/en/customization/internationalization/#vue-i-18-n
  • @IVOGELOV 这就是我所指的地方。我的问题是如何根据我的 vuex 商店中的状态更改“当前”。换句话说...如何在 Vuetify.js 中获取 vuex 状态
  • 您实际上应该朝相反的方向工作 - 如何在您的 updateLocale 突变中获取 this.$vuetify.lang 对象,以便您可以将其 current 属性更改为 newLocale
  • @IVOGELOV 我该怎么做?抱歉,学习了
  • 嗯,最简单的方法是如果你开始发送 this.$vuetify 作为你的突变的参数。

标签: vue.js vuex vuetify.js


【解决方案1】:

当您更改 i18n 中的语言环境时,您还应该在 Vuetify 中更改它:

export default new Vuex.Store({
  state: {
    locale: selectedLocale
  },
  mutations: {
    updateLocale(state, newLocale) {
      state.locale = newLocale
    }
  },
  actions: {
    changeLocale({ commit }, { newLocale, currentVueComponent }) {
      i18n.locale = newLocale
      currentVueComponent.$vuetify.lang.current = newLocale // <--- the important code
      commit('updateLocale', newLocale)
    }
  },
  plugins: [createPersistedState()]
})

【讨论】:

  • 非常感谢!但我得到一个错误....无法读取 $vuetify
  • 您正在发送 null 以获取 currentVueComponent 参数。
  • 我该如何改变呢?我需要更改 Vuetify.js 中的某些内容吗?
  • 你可以这样改——this.$store.dispatch("changeLocale", {newLocale: "es", currentVueComponent: this})
  • 非常感谢您的所有帮助,但我对每个答案都感到更加困惑。 :-) 我在哪里把 this.$store.dispatch("changeLocale", {newLocale: "es", currentVueComponent: this}) 放在我的 vuetify.js 中?
猜你喜欢
  • 2020-02-13
  • 2019-10-15
  • 2021-09-16
  • 2021-11-14
  • 1970-01-01
  • 2020-06-23
  • 2020-06-03
  • 2023-03-18
  • 2020-11-04
相关资源
最近更新 更多