1

I am using the vue-codemirror package to display css code on a website. The problem is that I don't understand how to update the state I get with vuex

  <div>
    <codemirror v-model="code" />
    <button @click="change">click</button>
    {{ $store.state.background }}
  </div>

  methods: {
    change() {
      Vue.set(this.$store.state, "background", "#242424");
    },
  },

  data() {
    return {
      code: dedent`
          /* Some example CSS */
          body {
            margin: ${this.$store.state.background};
            padding: 3em 6em;
          }
        `,
    };
  },

Vuex

export default new Vuex.Store({
  state: {
    background: "#000",
  },
});

I thought that the problem was reactivity and decided to use Vue.set when clicking on the click button, the value of {{ $store.state.background }} changes, but the code that is inside the data return does not change

You can also see this example in codesandbox

1
  • 3
    I think what you really want to do is make your code a computed value - that way when the state updates so will your value :) Commented Jan 28, 2022 at 20:54

1 Answer 1

2

Like @vanblart commented You can create computed property, instead data:

computed: {
  code() { return dedent(`
      /* Some example CSS */
      body {
        margin: ${this.$store.state.background};
        padding: 3em 6em;
      }
  `)
}

and in Vuex you can create action/mutation for setting values:

mutations: {
  addBkg(state, val) {
    state.background = val
  },
},
actions: {
  setBkg({ commit }, data) {
    commit("addBkg", data);
  },
},

and in methos dispatch that action:

change() {
  this.$store.dispatch("setBkg", "#242424");
},
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.