current position:Home>Using vuex in Vue projects

Using vuex in Vue projects

2022-04-29 16:10:31X Beichen North

explain

Here is only a simple record , I didn't sort it out in detail .

 

step

1、 Install the project in the root directory through the command vuex

npm install vuex --save-dev

2、 And then in src Create a new one in the directory store Folder , Create a new... In the folder index.js file , Enter the following code in this file :

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

Vue.use(Vuex);

const store = new Vuex.Store();

export default store;

3、 And then in main.js In the document , take store Global injection , In this way, you can use... In each component this.$store 了 , as follows :

import Vue from 'vue'
import App from './components/system/index/Index.vue';
import store from './store';

Vue.config.productionTip = false

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

4、 Return to our new store In the catalog index.js file , add to state Object and a test property , And then rewrite Store() Method instantiation code , as follows :

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

Vue.use(Vuex);

const state = {

    _defaultThemeColor: '#409EFF',       // The default theme background color 
};

const store = new Vuex.Store({
    state
});

export default store;

5、 After completing the above steps , We can use... In other components this.$store.state._defaultThemeColor To get us in index.js The attribute value defined in .

6、 But the way to get the value above is not the way we officially recommend , Officials provided one getters To get the value , The code is as follows :

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

Vue.use(Vuex);

const state = {

    _defaultThemeColor: '#409EFF',       // The default theme background color 
};

const getters = {

    _getDefaultThemeColor() {           // Name at will 
        return state._defaultThemeColor;
    }
};

const store = new Vuex.Store({
    state,
    getters
});

export default store;

7、 In addition to the value , We also deal with assignment , So we can pass mutations To modify our store The values defined inside , as follows :

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

Vue.use(Vuex);

const state = {

    _defaultThemeColor: '#409EFF',       // The default theme background color 
};

const getters = {

    _getDefaultThemeColor() {           // Name at will 
        return state._defaultThemeColor;
    }
};

const mutations = {

    _setDefaultThemeColor(state,value) {
        state._defaultThemeColor = value;
    }
};

const store = new Vuex.Store({
    state,
    getters,
    mutations
});

export default store;

8、 It's time to go through this.$store.commit('newNum',6) To change store It's worth .

copyright notice
author[X Beichen North],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291427264271.html

Random recommended