Vue uses vuex correctly

Vuex is a state management pattern developed specifically for Vue.js applications . Now large-scale projects basically need to use vuex, so I will write about how to configure and use vuex for people to discuss.

1. Install vuex

1. Terminal installation npm install vuex --save

2. Create a store folder, and create a new index.js and modules folder in the folder (vuex modularization)

The index.js code is as follows:

import Vue from 'vue'
import Vuex from 'vuex'
//引入模块
import a from './modules/a'
import b from './modules/b'
import c from './modules/c
export default new Vuex.Store({
  state: {
    axiosCancel: []
  },
  mutations: {},
  actions: {},
  modules: {
    a,
    b,
    c
  }
})

Place the store module in modules

For example, the code in module a (namespaced function: in order to solve the problem of naming conflicts between different modules, namespaced: true of different modules, and then when introducing getters, actions, and mutations in different pages, you need to add the module name to which it belongs)

const state = {

  basePath: 'homepage'
}

const mutations = {

  CHANGE_BASEPATH: (state, path) => {
    state.basePath = path
  }
}

const actions = {

  changeBasePath({ commit }, path) {
    commit('CHANGE_BASEPATH', path)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

3 main.js file introduction

code show as below:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from '@/store'
Vue.config.productionTip = false
Vue.prototype.$echarts = echarts
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

Two, use vuex

 Create a new demo code as follows:

<template>
  <div class="">a模块调用mutation的值:{
   
   { basePath }}</div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  components: {},
  data() {
    return {
    }
  },
  computed: {
    ...mapState({
      'basePath': state => state.a.basePath
    })

  },
  watch: {},
  created() {
    // 使用a模块的state
    console.log(this.$store.state.a)
    // 使用a模块的mutation(不推荐这样写,推荐写成对象的形式{path:'qqqq'},这样可以传多个参)
    this.$store.commit('a/CHANGE_BASEPATH', 'qqqq')
    // 使用a模块的action
    this.$store.dispatch('a/changeBasePath', 'bbbb')
  },
  mounted() {},
  methods: {}
}
</script>
<style lang="scss" scoped>
</style>

Put the state in computed so that the value of the state changes and the value of the dom also changes

 

Guess you like

Origin blog.csdn.net/yinzisang/article/details/122303905