Vuex knowledge

Disclaimer: If you have any objection to this article, then please write your comments in the article comments at. If you find this article interesting, please share and forward, or you can look at, you acknowledge and encouragement of our articles. Wish everyone in the programming this road, farther and farther. https://blog.csdn.net/weixin_44369568/article/details/91459231

Vuex

1. What is vuex?
  • The heart of every Vuex application is to store (warehouse). "Store" is basically a container that contains most of the state (state) of your application.
2, initialize vuex

(1) download vuex

cnpm i vuex -D

(2) build a store folder (store / index.js)

// 初始化vuex

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

// 引入module
import app from './module/app';

Vue.use(Vuex);

// 生成一个vuex实例
export default new Vuex.Store({
  modules: {
    app
  }
})

(3) build a module file in the store folder in the folder used to store data (store / module / app.js)

// 存放数据的地方
const state = {
  num: 100
}

// 派生数据(很少用)
const getters = {
    doubleNum(state){
        return state.num*2
    }
}

// 同步改变
const mutations = {
  changeNum(state, payload){
    state.num = payload;
  }
}

// 异步改变
const actions = {
    <!--changeNumAsync(context, payload){-->
        
    <!--}-->
    changeNumAsync({commit}, payload){
        commit('changeNum', payload)
    }
}

export default {
  // 命名空间
  namespaced: true, // 配合module使用
  state,
  actions,
  getters,
  mutations
}

(4) is introduced inside the store in main.js

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

import store from './store'

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

(5) use the page

<template>
  <div>
    <button @click="changeNum('+')">+</button>
    <span>{{num}}</span>
    <button @click="changeNum('-')">-</button>
  </div>
</template>
<script>
  export default {
    name: 'app',
    computed: {
      num() {
        return this.$store.state.app.num
      }
    },
    methods: {
      changeNum(type) {
        if (type == '+') {
          // this.$store.commit('changeNum', this.num+1)
          this.$store.dispatch('changeNumAsync', this.num+1)
        } else {
          this.$store.commit('changeNum', this.num-1)
        }
      }
    },
    mounted(){
      console.log(this.$store)
    }
  }
</script>

Guess you like

Origin blog.csdn.net/weixin_44369568/article/details/91459231