【发布时间】: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