vuex2.0基本使用---1、初始版

1、初始化项目:vue init webpack vuex_demo
2、安装vuex:npm install vuex -D
3、在src文件夹里新建一个vuex文件夹
4、在vuex文件夹里新建一个store.js的文件
5、在store.js里写上以下代码:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const actions = {
  increment: (context) => {
    context.commit('INCREMENT')
  },
  decrement: (context) => {
    context.commit('DECREMENT')
  }
}

const mutations = {
  INCREMENT: state => state.count++,
  DECREMENT: state => state.count--
}

var state = {
  count: 0
}

export default new Vuex.Store({
  actions: actions,
  mutations: mutations,
  state: state
})

6、在main.js里加上以下代码:

import Vuex from 'vuex'
import store from './vuex/store'
Vue.use(Vuex)

7、在components文件夹里新建一个Count.vue组件
8、在Count.vue组件写上以下代码:

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

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

9、启动项目就可以查看效果了

发布了123 篇原创文章 · 获赞 4 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/yuzhiboyouzhu/article/details/79171740