使用Vuex编写简单案例--实现计数器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29918313/article/details/83148823

首先需要在项目中安装vuex,命令是npm install --save vuex

然后再main.js文件里面,通过Vue.use(Vuex)来使用vuex,前提是在该文件中引入Vuex,即import Vuex from 'vuex';仓库store 包含了应用的数据(状态)和操作过程,需要定义store,命令是:const store = new Vuex.Store({  }),main.js文件如代码所示:

import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'

Vue.config.productionTip = false
Vue.use(Vuex)

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

new Vue({
  store,
  render: h => h(App)
}).$mount('#app')

其中,在任何组件中都可以通过$store.state.count来读取;因此我要在页面中读取store中的count值得时候,直接在计算属性中this.$store.state.count即可

在组件中,来自store的数据只能读取,不能手动改变,改变store中数据的唯一途径就是显示的提交mutations,mutations用来直接修改state的数据,因此组件代码如下所示:

<template>
  <div id="app">
    <p>{{ count }}</p>
    <p>
      <button @click="increment">+</button>
      <button @click="decrement">-</button>
    </p>
  </div>
</template>

<script>

export default {
  name: 'app',
  computed: {
      count() {
          return this.$store.state.count
      }
  },
  methods: {
      increment () {
          this.$store.commit('increment')
      },
      decrement () {
          this.$store.commit('decrement')
      }
  }
}
</script>

这就实现了一个简单的计数器,关键是在该案例中体会vuex中store等的使用。

猜你喜欢

转载自blog.csdn.net/qq_29918313/article/details/83148823