简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM