search
HomeWeb Front-endVue.jsA brief analysis of the use of centralized state management Vuex

How to use Vuex with centralized state management? The following article will take you to understand vuex and briefly talk about how to use vuex. I hope it will be helpful to you!

A brief analysis of the use of centralized state management Vuex

1.What is vuex

A dedicated implementation of centralized state management in Vue The Vue plug-in can centrally manage (read/write) the shared state of multiple components in a Vue application. It is also a method of inter-component communication and is suitable for any inter-component communication

2. When to use Vuex

1. Multiple components depend on the same state

2. Behaviors from different components need to change the same state

2.1 How to use Vuex

First of all, we need to know that if you use Vuex, there is a high probability that two or more components will need to share a set of data. /status, so first we need to prepare two components (Count and Person respectively), and then we need to add a store file in the src directory, because Vuex relies on the store to perform a series of preparation tasks

2.2Count component

In this component we can see map...a ​​bunch of things, here we have to talk about the four ## in vuex #map, I have put how to use the map method at the end. Here we only introduce the functions of this component. Count is a component with "powerful" calculation functions. It can amplify the final number 10 times, and it can be an odd number. The operation can be delayed, which is extremely "powerful"

<template>
  <div>
    <h3 id="当前和为-sum">当前和为:{{sum}}</h3>
    <h3 id="当前和为-放大-倍-bigSum">当前和为:放大10倍:{{bigSum}}</h3>
    <h3 id="我在-school-学习-subject">我在{{school}},学习{{subject}}</h3>
    <h3 id="下方组件的总人数-personList-length">下方组件的总人数{{personList.length}}</h3>

    <select v-model.number="num">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment(num)">+</button>
    <button @click="decrement(num)">-</button>
    <button @click="incrementOdd(num)">奇数+</button>
    <button @click="incrementWait(num)">500ms后再+</button>
  </div>
</template>
<script>
// 引入mapState等
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
  name: "Count",
  data() {
    return {
      num: 1 // 用户选择的数字
    };
  },
  computed: {
    // 使用mapState生成计算属性,从state种读取数据(...mapstate()的意思是将其内的对象全部展开的计算属性里面)
    // ...mapState({ sum: "sum", school: "school", subject: "subject" }), // 对象写法
    ...mapState(["sum", "school", "subject", "personList"]), // 数组写法
    // 使用mapGetters生成计算属性,从getters种读取数据
    // ...mapGetters(["bigSum"]), // 数组写法
    ...mapGetters({ bigSum: "bigSum" }) // 数组写法
  },
  methods: {
    // 借助mapMutations生成对应的方法,方法种会调用相应的commit去联系mutations
    ...mapMutations({ increment: "JIA", decrement: "JIAN" }), // 对象式
    ...mapActions({ incrementOdd: "jiaodd", incrementWait: "jiaWait" }) //数组式
    // ...mapActions(["jiaodd", "jiaWait"]) //数组式简写
  },
  mounted() {
  }
};
</script>
<style>
button {
  margin-left: 5px;
}
</style>

2.3Person component

ThePerson component is added by "powerful" people Function, he can add your relatives and friends according to his own wishes

<template>
  <div>
    <h3 id="人员列表">人员列表</h3>
    <h3 id="Count组件的求和为-sum">Count组件的求和为{{sum}}</h3>
    <input type="text" placehodler="请输入名字" v-model="name">
    <button @click="add">添加</button>
    <ul>
      <li v-for="p in personList" :key="p.id">{{p.name}}</li>
    </ul>
  </div>
</template>
<script>
import { nanoid } from "nanoid";
export default {
  name: "Person",
  data() {
    return {
      name: ""
    };
  },
  computed: {
    personList() {
      return this.$store.state.personList;
    },
    sum() {
      return this.$store.state.sum;
    }
  },
  methods: {
    add() {
      const personObj = { id: nanoid(), name: this.name };
      this.$store.commit("ADD_PERSON", personObj);
      this.name = "";
    }
  }
};
</script>

2.4 Introduce components

Introduce these two components into the App respectively Component

<template>
  <div class="container">
    <Count></Count>
    <Person/>
  </div>
</template>

<script>
import Count from "./components/Count";
import Person from "./components/Person";
export default {
  name: "App",
  components: { Count, Person }
};
</script>

2.5 Configure index.js under the store folder

To create a new index.js file under the store folder, Then write the following code into the index file. First, introduce vue and vuex, and then use action to respond. Here we can receive two parameters:

context and valueThey separate the context and the value passed in. We can find everything in the state we configured on the context. This is what is on the context, and the value. The value of value here is 1

A brief analysis of the use of centralized state management Vuex

// 创建VUex种的store核心
import Vue from &#39;vue&#39;
// 引入Vuex
import Vuex from &#39;vuex&#39;
// 使用vuex插件
Vue.use(Vuex)
// 准备actions——用于组件内的动作响应
const actions = {
    // 奇数加法
    jiaodd(context, value) {
        if (context.state.sum % 2) {
            context.commit(&#39;JIA&#39;, value)
        }
    },
    // 延迟加
    jiaWait(context, value) {
        setTimeout(() => {
            context.commit("JIA", value)
        }, 500);
    },
}
// 准备mutations——用于数据操作
const mutations = {
    JIA(state, value) {
        state.sum += value
    },
    JIAN(state, value) {
        state.sum -= value
    },
    ADD_PERSON(state, value) {
        console.log(&#39;mustations种的ADD_PERSON被调用&#39;,state.personList);
        state.personList.unshift(value)
    }
}
// 准备state——用于数据的储存
const state = {
    sum: 0, // 当前和
    school: &#39;山鱼小学&#39;,
    subject: &#39;前端&#39;,
    personList:[{id:&#39;001&#39;,name:&#39;张三&#39;}]
}
// 用于加工state种的数据
const getters = {
    bigSum(state) {
        return state.sum * 10
    }
}
// 创建store并且暴露store
export default new Vuex.Store({
    // actions: actions,// 前后名称一样所以可以触发简写模式
    actions,
    mutations,
    state,
    getters
});

2. The use of four map methods

1.mapState: Used to help us map the data in state to calculated attributes

computed: {
    // 使用mapState生成计算属性,从state种读取数据(...mapstate({})的意思是将其内的对象全部展开的计算属性里面)
    ...mapState({ sum: "sum", school: "school", subject: "subject" }), // 对象写法
        
    // ...mapState(["sum", "school", "subject"]), // 数组写法
  }

2.mapGetters: Used to help us map the data in getters to calculated properties

computed: {
    // 使用mapGetters生成计算属性,从getters种读取数据
    ...mapGetters({bigSum:"bigSum"})
    ...mapGetters(["bigSum"])
  }

3.mapMutations:Use To help us generate methods to communicate with mutations, including the function $store.commit()

methods: {
    // 借助mapMutations生成对应的方法,方法种会调用相应的commit去联系mutations
    ...mapMutations({ increment: "JIA", decrement: "JIAN" }), // 对象式
    // ...mapMutations(["JIA", "JIAN"]), // 数组式(button的名字和vuex里面的名字必须统一)
  },

3.mapActions : Used to help us generate methods to communicate with mutations, including the function of $store.commit()

  methods: {
     // 借助mapActions生成对应的方法,方法种会调用相应的dispath去联系actions
    ...mapActions({ incrementOdd: "jiaodd", incrementWait: "jiaWait" }), //对象式
    // ...mapActions(["jiaodd", "jiaWait"]) //数组式
  },

Note: When using mapActions and mapMutations, if necessary Passing parameters requires passing the parameters when binding the event in the template, otherwise the parameters are event objects.

(Learning video sharing:

vuejs introductory tutorial, Basic programming video)

The above is the detailed content of A brief analysis of the use of centralized state management Vuex. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

Vue.js vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to jump a tag to vueHow to jump a tag to vueApr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool