Home > Enterprise >  What is the best way to use $state in Vue.js?
What is the best way to use $state in Vue.js?

Time:09-16

I used to do AngularJS and now I wanna try to work with Vue.js.

But I have a simple question: what is the best way to use and access states? I saw so many solutions on Google but I can't find which one is the best for a beginner.

I used to use states like this :

$state.go('homework', { homework: homework.homework});

Can you give me an exemple of this code in Vue? Basically, go to homework and give him an homework.

CodePudding user response:

In Vue.js it works with Vuex, the management library. You can find a documentation for state management in Vue.js here or and for Vuex here.

Example from the documentation for Vuex:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count  
    }
  }
})

Use your Vuex store in your app:

new Vue({
  el: '#app',
  store
})

Access your state in a component:

this.$store.state.count

Change the state according to the example (state.count ):

this.$store.commit('increment')

Edit:

To complete the answer with a example for your question. Declare

const store = new Vuex.Store({
  state: {
    homework: "Example"
  },
  mutations: {
    setNewHomework (state, newHomework) {
      state.homework = newHomework
    }
  }
})

Set a new state for homework:

this.$store.commit('setNewHomework', 'New Homework')

CodePudding user response:

With $state.go I believe you are using ui-router. In that case you should check out Vue Router. It works quite similar.

  • Related