[vue2] Installation, configuration and use of vuex

I. Introduction

Data sharing can be realized by using vuex.

2. Installation

Create a new terminal in vscode to install vuex. Since vue2 cannot use the version of vuex4, you need to specify version 3 when installing

npm i vuex@3

3. vuex workflow

The core of vuex includes actions, mutations, and state.

①state is used to store data;

②actions are used to respond to component events, and can also process data or make back-end requests, that is to say, calling the dispatch method in the component can trigger the method in actions;

③ Mutations are used to operate the state, and the commit method is called in actions to call mutations.

④Others: When no additional data processing is required, the commit method can be called directly in the component to trigger the method in mutations

4. Configuration

Step 1: Create a new folder store, and create a new index.js file under the folder

Step 2: Complete the configuration in index.js: data and events have not been configured yet

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

// 用来存储数据
const state = {

}
// 响应组件中的事件
const actions = {

}
// 操作数据
const mutations = {

}
// 用来将state数据进行加工
const getters = {

}
// 新建并暴露store
export default new Vuex.Store({
    state,
    actions,
    mutations,
    getters
})

Step 3: Introduce in main.js

import Vue from 'vue'
import App from './App.vue'
import store from './store/index';

Vue.config.productionTip = false

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

5. Use

5.1. Conventional writing

1、state

Use $store.state.xxx to get the value in the component, for example:

<li v-for="p in $store.state.person" :key="p.id">
   姓名:{
   
   { p.personName }} 年龄:{
   
   { p.age }}
   <button @click="deletePerson(p.id)">删除</button>
</li>

index.js of vuex:

const state = {
    person: [
        { id: nanoid(), personName: "张三", age: 18 },
        { id: nanoid(), personName: "张4", age: 28 },
        { id: nanoid(), personName: "张5", age: 38 },
    ]
}

2、getter

Use $store.getters.xxx in the component to get the return value in the getters

<span> 学生年龄总和:{
   
   { $store.getters.getAllPersonAge }} </span>

index.js:

// 用来将state数据进行加工:类似于computed
const getters = {
    getAllPersonAge(state) {
        var sumAge = 0;
        state.person.forEach(element => {
            sumAge += element.age
        });
        return sumAge
    }
}

3、actions

Use this.$store.dispatch("aaa", xxx) in the component to trigger the aaa method in actions, the parameter is xxx

<input type="text" v-model="newPerson" />
<button @click="addPerson">添加</button>

addPerson() {
   if (this.newPerson == "") {
      alert("请输入姓名");
      return;
   }
   this.$store.dispatch("addPerson", this.newPerson);
   this.newPerson=""
},

index.js

// 响应组件中的事件
const actions = {
    //添加人员
    addPerson(content, value) {
        console.log(value)
        const person = {
            id: nanoid(),
            personName: value,
            age: 18//暂时写死
        }
        content.commit("addPerson", person)
    }
}

4、mutations

In the component:

<button @click="deletePerson(p.id)">删除</button>

deletePerson(id) {
      this.$store.commit("deletePerson", id);
},

index.js

const mutations = {
    addPerson(_, value) {
        this.state.person.unshift(value)
    },
    deletePerson(_, id) {
        const newArr = this.state.person.filter(p => {
            return p.id != id
        })
        this.state.person = newArr
    }
}

5.2 Four map writing methods

All the above-mentioned writing methods need to manually write this.$store.xxx, which is cumbersome. You can introduce four maps of vuex into the component to simplify the operation

Introduced in the component:

import { mapState, mapActions, mapGetters, mapMutations } from "vuex";

use:

computed: {
    ...mapState(["person"]),
    ...mapGetters(["getAllPersonAge"]),
},
methods: {
    ...mapActions({
    addPerson1: "addPerson",   //第一个为本地方法名,第二个参数为actions中的方法名
}),
    ...mapMutations(["deletePerson"]),//当本地和index.js中的方法名一致时,可以简化成数组写法
},

Use: directly use the parameter name defined above

  <input type="text" v-model="newPerson" />
    <button @click="addPerson1(newPerson)">添加</button>
    <ul>
      <li v-for="p in person" :key="p.id">
        姓名:{
   
   { p.personName }} 年龄:{
   
   { p.age }}
        <button @click="deletePerson(p.id)">删除</button>
      </li>
    </ul>
  <span> 学生年龄总和:{
   
   { getAllPersonAge }} </span>

5. Others

The above is all the introduction of vuex, let's make progress together.

Guess you like

Origin blog.csdn.net/weixin_44431073/article/details/125097284