mutations.js文件书写规范及模板调用此文件书写方法

1)mutations.js代码如下

const mutations={
    add(state){
        state.count++
    },
    reduce(state){
        state.count--
    }
}

 2)在button中,通过commit直接调用。

<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>

 放在组件home.vue中案例代码

<template>
  <div class="Home">
    <button @click="$store.commit('add')">+</button>
    <button @click="$store.commit('reduce')">-</button>

    <p>引用state选项一个变量:{{count}}</p>
    </div>
</template>
<script>
export default {
  name: 'Home',
  data () {
    return {
      msg: 'Home.vue 组件'
    }
  },
  computed: {
    // 调用是vuex,state选项文件rootState.js中声明变量
    count () {
      console.log('this结构:' + this.$store.state.count)
      return this.$store.state.count
    }
  }
}
</script>

猜你喜欢

转载自www.cnblogs.com/asplover/p/11355279.html