Vuex import local JSON file into state

Viewed 30

I want to import data from my local JSON file into a state value setting.

store/index.js

import { createStore} from 'vuex'

export default createStore({
  state: {
    settings: {}
  }
})

assets/json/settings.json

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

It also has to be reactive to work with computed in Vue. This means it should use maybe something like fs or so to save the changes into the JSON file. I use Vuex because I want to change data across multiple components.

How I can set the JSON value into the state.settings value?

1 Answers

you can import directly from a json file like you would a js file

which you can then return from the state initialiser

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
    }
  }
})

just be sure you have

"resolveJsonModule": true

in your js compiler options

the browser shouldn't be editing this file directly so save changes in a cookie, local storage,session storage, or via a webservice call to your server

Related