153-Vue中的vuex内的辅助函数——mapState,mapGetters,mapMutations,mapActions的用法
首先查看目录:
此文章所涉及到的代码:src/components/Comp1.vue
store/index.js
views/HomeView.vue
其它的都是初建的代码,未做改动,此处不展示。
Comp1.vue代码如下:
- <template>
- <div>
- <p>{{num}}p>
- <p>{{title}}p>
- <p>{{dbNum}}p>
- <button @click="chanNum(1)">同步按钮button>
-
- <button @click="asyncChanNum(100)">异步按钮button>
-
- div>
- template>
-
- <script>
- import { mapMutations, mapState,mapActions,mapGetters } from 'vuex'
- export default {
- methods:{
- ...mapMutations(['chanNum']), // 同步
- // add(){
- // this.$store.commit('chanNum',10)
- // },
- ...mapActions(['asyncChanNum']), // 异步
- // add1(){
- // this.$store.dispatch('asyncChanNum',100)
- // }
- },
- computed:{
- ...mapState(['num','title']),
- // num(){
- // return this.$store.state.num
- // }
- ...mapGetters(['dbNum']),
- // dbNum(){
- // return this.$store.getters.dbNum
- // }
- },
- data () {
- return {
-
-
- }
- }
- }
- script>
-
- <style lang = "less" scoped>
-
- style>
store/index.js代码如下:
- import Vue from 'vue'
- import Vuex from 'vuex'
-
- Vue.use(Vuex)
-
- export default new Vuex.Store({
- state: {
- num:11,
- title:'标题'
- },
- getters: {
- dbNum(state){
- return state.num*2
- }
- },
- mutations: { // 同步
- chanNum(state,payload){
- state.num+=payload
- }
- },
- actions: { // 异步
- asyncChanNum({commit},payload){
- setTimeout(()=>{
- commit('chanNum',payload)
- },1000)
- }
- },
- modules: {
- }
- })
views/HomeView.vue代码如下:
- <template>
- <div class="home">
- <HelloWorld />
- div>
- template>
-
- <script>
- // @ is an alias to /src
- import HelloWorld from '@/components/Comp1.vue'
-
- export default {
- name: 'HomeView',
- components: {
- HelloWorld
- }
- }
- script>
下面显示操作步骤:
最终效果如下: