【问题标题】:How to access nuxt `$config` in Vuex state? Only access method is through store actions methods?如何在 Vuex 状态下访问 nuxt `$config`?唯一的访问方法是通过存储操作方法吗?
【发布时间】:2021-09-14 01:01:17
【问题描述】:

我习惯使用 dotenv 库来使用 .env 文件,但我必须更改 runtimeConfig,因为我意识到很容易暴露我的项目密钥。

在我最新的项目中,我使用了 nuxt "^2.14" 并且模式是 SPA。 所以我只像这样在nuxt.config.ts中使用“publicRuntimeConfig”。

.env

Test_BASE_URL:'https://test.org'

nuxt.config.ts

export default {
   publicRuntimeConfig:{baseURL: proccess.env.Test_BASE_URL||''}
}

我可以像在 vue 文件中那样使用 env。

sample.vue

<script>
export default {
 mounted(){
  console.log(this.$config.baseURL)
 }
}
</script>

但我不能在商店的状态中使用“$config”。 我试着写下它,但它总是返回“undefied”

index.ts

export const state = (context) => ({
  url:context.$config
})

我已经推荐了这些人solutions 并通过 actions 方法改变状态的值。 我用过 SPA,所以我做了像 'nuxtServerInit' 这样的方法作为插件。

插件/clientInit.ts

import {Context} from "@nuxt/types";

export default function (context:Context) {
 context.store.dispatch('initEnvURL',context.$config)
}

index.ts

interface State {
 testURL: string
}
const state = () => ({
 testURL:''
})
const mutations = {
 setTestURl(state:State,config:any) {
  state.testURL = config.baseURL
}
const actions = {
 initEnvURL({commit},$config) {
 commit('setTestURl',$config)
}
}
export default {state,mutations,actions}

我通过上面的操作方法成功地改变了状态值, 但我不知道为什么“上下文”不能直接使用存储/状态对象。 有谁知道如何在商店/状态中使用 $config ? 还是只能通过上述操作方法使用 $config ?

【问题讨论】:

    标签: javascript typescript vue.js nuxt.js vuex


    【解决方案1】:

    那是因为在 Vuex 中,只有动作才能真正接收应用上下文。 State、Mutations 和 Getter 无法通过设计访问它。

    您的初始状态应该是无上下文的,即具有不依赖于运行时执行的值。

    突变是无状态的,它们只需要一个参数并更新状态。就这样。上下文参数应该来自调用者。

    Getter 只是响应式状态转换,不应依赖于上下文属性,否则会干扰 Vuex 模块状态。


    所以是的,您必须在 nuxtServerInit 操作(或来自 SPA 应用程序的插件)中初始化您的商店:

    nuxtServerInit({ store, config } ) {
       store.commit('UPDATE_BASE_URL', config.baseUrl)
    }
    

    【讨论】:

    • 感谢您的回答!我真的明白为什么 $config 不能在 store/state 中使用。我注意到我不了解 Nuxt 生命周期和 vuex 系统。对此,我真的非常感激!谢谢!!
    猜你喜欢
    • 2021-07-01
    • 1970-01-01
    • 2021-03-28
    • 2011-06-21
    • 2021-06-17
    • 2021-04-21
    • 2019-09-17
    • 2020-10-26
    • 2021-10-19
    相关资源
    最近更新 更多