vuex全家桶系列01-vuex以及基本使用

216 阅读1分钟

1.安装vuex

npm install vuex -S 或者 vue add vuex

🍊store中的代码:

  • 引入Vuex后需要使用Vue.use(Vuex)去使用
  • 然后通过new Vuex.Store创建一个store,然后暴露出去。
//src/store/index.js

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count:0
  },
  mutations: {
    add(state){
      state.count = state.count+1; 
    },
    decrease(state){
      state.count = state.count - 1 ;
    }
  },
  actions: {

  },
  modules: {
  }
})

🍊main.js中的代码:

  • new Vue中可以看到router,还有store都被挂载到了new Vue上面去,后面就可以通过this.$store或者this.$router来获得
//main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false

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

2.Vuex的基本使用:

这里就以Home.vue实现加减计数为例,方便理解

  • 第一种:常规方法,computed中通过函数返回

  • 第二种:mapState,通过matState和箭头函数

  • 第三种:matState+数组,这个时候count属性名要和store/index.js中的保持一致。

    。引申:拿到vuex的属性,可以在computed中通过this来加入组件自己的data属性

<template>
<div class="home">
    我是home页
    <br />
    {{count}}
    <div>
        <button @click="add">+ 1</button>
    </div>
    <div>
        <button @click="decrease">-1</button>
    </div>
</div>
</template>

<script>
import {
    mapState
} from 'vuex';

export default {
    name: 'Home',
    data() {
        return {
            localCount: 12
        }
    },
  	//🌵第1种:
    // computed: {
    //     count() {
    //         return this.$store.state.count
    //     },
    // },
  	//🌵第2种:
    // computed: mapState({
    //     count: state => state.count
    // }),
		//🌵引申:
    // computed: {
    //     count() {
    //         return this.$store.state.count + this.localCount
    //     }
    // },
    //🌵第3种
    computed: mapState([
        "count"
    ]),
    methods: {
        add() {
            this.$store.commit('add');
        },
        decrease() {
            this.$store.commit("decrease")
        }
    },
};
</script>