Vuex导入本地JSON文件到状态



我想将数据从本地JSON文件导入到状态值设置中。

存储/index.js

import { createStore} from 'vuex'
export default createStore({
state: {
settings: {}
}
})

资产/json/settings.json

{
"theme": "dark",
"loggedIn": true,
"mobile": false,
}

它还必须是响应性的,以便在Vue中使用computed。这意味着它应该使用fs之类的东西将更改保存到JSON文件中。我使用Vuex是因为我想跨多个组件更改数据。

如何将JSON值设置为状态。设置值?😅

你可以像导入js文件一样直接导入json文件

可以从状态初始化器

返回
import settings from "./settings.json";
export default createStore({
state(){ //note: state should always be a function to create a state not the state itself
return {
settings: settings
}
}
})

一定要有

"resolveJsonModule": true

在你的js编译器选项

浏览器不应该直接编辑这个文件,所以将更改保存在cookie,本地存储,会话存储或通过webservice调用服务器

最新更新