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教程22:mapState、mapActions、mapGetters #23

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

Vue教程22:mapState、mapActions、mapGetters #23

chencl1986 opened this issue Mar 18, 2019 · 0 comments

Comments

@chencl1986
Copy link
Owner

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

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

map映射函数

map映射函数 映射结果
mapState 将state映射到computed
mapActions 将actions映射到methods
mapGetters 将getters映射到computed

mapState的使用

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

首先需要引入map函数:

import { mapState, mapActions, mapGetters } from 'vuex'

在computed中使用mapState:

computed: {
  ...mapState(['a', 'b']),
}

就可以代替这段代码:

computed: {
  a() {
    return this.$store.state.a
  },
  b() {
    return this.$store.state.b
  },
}

mapActions的使用

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

在methods中添加addA和addB的映射

methods: {
  ...mapActions(['addA', 'addB']),
},

等价于:

methods: {
  addA(n) {
    this.$store.dispatch('addA', n)
  },
  addB(n) {
    this.$store.dispatch('addA', n)
  },
}

mapGetters的使用

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

在computed中添加count的映射:

computed: {
  ...mapGetters(['count'])
}

等价于:

computed: {
  count() {
    return this.$store.getters.count
  }
}
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