Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue教程21:Vuex Getter #22

Open
chencl1986 opened this issue Mar 18, 2019 · 0 comments
Open

Vue教程21:Vuex Getter #22

chencl1986 opened this issue Mar 18, 2019 · 0 comments

Comments

@chencl1986
Copy link
Owner

阅读更多系列文章请访问我的GitHub博客,示例代码请访问这里

该节教程代码可通过npm start运行devServer,在http://localhost:8080/#/index查看效果

Getter的基本使用

代码示例:/lesson21/src/index.js

Vuex中的Getter的作用类似于Vue中的Computed,可以实现在state变化时自动计算出一个新的结果。
在store中配置一个Getter:

getters: {
  count (state) {
    return state.a + state.b
  }
}

代码示例:/lesson21/src/components/Index.vue

在组件Index中,可以通过$store.getters.count就可以读取到相应的值。

<div>count from getters: {{$store.getters.count}}</div>

为了方便使用,通常可以把Getter配置到Computed中:

computed: {
  countFromComputed() {
    return this.$store.getters.count
  }
}

在Template中引用:

<div>count from computed: {{countFromComputed}}</div>

利用Computed更新State

因为Computed属性支持get和set方法,所以能够使用set方法更新State。

首先在Store中设置actions和Mutations。

代码示例:/lesson21/src/store/index.js

mutations: {
  addA (state, n) {
    state.a += n
  },
  addB (state, n) {
    state.b += n
  },
},
actions: {
  addA ({commit}, n) {
    commit('addA', n)
  },
  addB ({commit}, n) {
    commit('addB', n)
  },
},

Index.vue模板中添加<input type="button" value="count+5" @click="addCount(5)" />,调用一个addCount方法,在addCount方法中让countFromComputedSet属性加5。
在computed属性中接收到结果后,将增加的5分配给a属性。

countFromComputedSet: {
  get() {
    return this.$store.getters.count
  },
  set(value) {
    this.$store.dispatch('addA', 5)
  },
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant