在 Vue.js 中使用 $state 的最佳方式是什么?

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

我以前是 AngularJS,现在我想尝试使用 Vue.js

但我有一个简单的问题:使用和访问状态的最佳方式是什么?我在 Google 上看到了很多解决方案,但我找不到最适合初学者的解决方案。

我曾经使用这样的状态:

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

你能给我一个 Vue 中这段代码的例子吗?基本上,去写作业,给他做作业。

Vue.js 中,它与管理库 Vuex 一起使用。您可以在 Vue.js here or and for Vuex here.

中找到状态管理文档

Vuex 文档中的示例:

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

在您的应用中使用您的 Vuex 商店:

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

在组件中访问您的状态:

this.$store.state.count

根据例子改变状态(state.count++):

this.$store.commit('increment')

编辑:

用你的问题的例子来完成答案。声明

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

homework 设置新状态:

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

使用 $state.go 我相信您正在使用 ui-router。 在那种情况下,您应该查看 Vue Router。它的工作原理非常相似。