vuex2.0基本使用---2、进阶版

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) => { 数组写法
  INCREMENT: (context) => {
    context.commit('INCREMENT')
  },
  DECREMENT: (context) => {
    context.commit('DECREMENT')
  },
  INCREMENTTWO: (context) => {
    console.log('context:======', context)
    context.commit('INCREMENTTWO')
  }
}

// 处理状态(数据)变化
const mutations = {
  INCREMENT: state => state.count++,
  DECREMENT: state => state.count--,
  INCREMENTTWO: (state) => {
    state.count = state.count + 2
    return state.count
  }
}

var state = {
  count: 0
}

const getters = {
  count (state) {
    return state.count
  }
}

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

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>
      <button @click="decrementTwo()">+2</button>
    </p>
  </div>
</template>

<script>
import {mapActions, mapGetters} from 'vuex'
// console.log('mapActions:======', mapActions)
// console.log('mapGetters======', mapGetters)
export default {
  name: 'Count',
  methods: {
    // 数组写法:
    // ...mapActions(['increment', 'decrement'])
    // 对象写法:
    ...mapActions({
      increment: 'INCREMENT',
      decrement: 'DECREMENT',
      decrementTwo: 'INCREMENTTWO'
    })
  },
  computed: {
    // 数组写法:
    // ...mapGetters(['count'])
    // 对象写法:
    ...mapGetters({
      count: 'count'
    })
  }
}
</script>

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

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

猜你喜欢

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