search
HomeWeb Front-endJS TutorialHow to use vuex? Detailed explanation of vuex usage steps (with code)

How to use vuex: 1. Use the Vue scaffolding tool to build the project; 2. Use the npm package management tool to install vuex; 3. Create a new store folder and create a new "store.js" under the folder. file; 4. Introduce vue and vuex into the file.

How to use vuex? Detailed explanation of vuex usage steps (with code)

How to use vuex? This time I will bring you a detailed explanation of the steps to use vuex (with code), what are the precautions when using vuex, the following is a practical case, let's take a look.

What is Vuex?

vuex is a centralized state management architecture specially designed for vue.js. state? I understand it as the part where the attributes in data need to be shared with other vue components, which is called state. Simply put, it is the attributes that need to be shared in data.

Introduce Vuex (provided that the project has been built with the Vue scaffolding tool)

1. Use the npm package management tool to install vuex. Just enter the following command in the control command line.

 npm install vuex --save

It should be noted that –save must be added here, because we will use your package in the production environment.

2. Create a new store folder (this is not necessary), and create a new store.js file under the folder, and introduce our vue and vuex into the file.

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

3. Use our vuex and reference it with Vue.use after importing it.

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

Through these three steps, even if vuex is successfully referenced, we can then have fun.

4. Introduce the new vuex file into main.js

 import storeConfig from './vuex/store'

5. Then, add the store object when instantiating the Vue object:

 new Vue({
  el: '#app',
  router,
  store,//使用store
  template: '<app></app>',
  components: { App }
 })

Let’s take a demo

1. Now we add a constant object to the store.js file. The store.js file is the file when we introduced vuex.

 const state = {
  count:1
 }

2. Use export default to encapsulate the code so that it can be referenced externally.

 export default new Vuex.Store({
  state
 });

3. Create a new vue template, located in the components folder, named count.vue. In the template, we introduce the store.js file we just created, and use {{$store.state.count}} to output the count value in the template.

 <template>
  <p>
   </p>
<h2 id="msg">{{msg}}</h2>
   <hr>
   <h3 id="store-state-count">{{$store.state.count}}</h3>
  
 </template>
 <script>
  import store from &#39;@/vuex/store&#39;
  export default{
   data(){
    return{
     msg:&#39;Hello Vuex&#39;,
    }
   },
   store
  }
 </script>

4. Add two methods to change state in the store.js file.

const mutations={
  add(state){
   state.count+=1;
  },
  reduce(state){
   state.count-=1;
  }
 }

The mutations here are written in a fixed way, meaning they can be changed, so you don’t have to worry. Just know that the way we want to change the value of state must be written in mutations.

5. Add two buttons to the count.vue template and call the methods in mutations.

 <p>
  <button>+</button>
  <button>-</button>
 </p>

By previewing in this way, you can add or subtract the count in vuex.

state access state object

const state, this is what we call the access state object, it is our SPA (Single Page Application) shared value in .

The learning status object is assigned to the internal object, that is, the value in stoe.js is assigned to the value in data in our template. There are three assignment methods

1. Direct assignment through computed calculated attributes

The computed attribute can perform operations on the values ​​in the data before outputting Change, we will use this feature to assign the state value in store.js to the data value in our template.

 computed:{
  count(){
   return this.$store.state.count;
  }
 }

What needs to be noted here is that return this.$store.state.count must be written in this sentence, otherwise you will not find $store. This way of writing is easy to understand, but it is more troublesome to write. Let's take a look at the second way of writing.

2. Assign value through mapState object

We must first use import to introduce mapState.

import {mapState} from 'vuex';

Then write the following code in the computed property:

 computed:mapState({
   count:state=>state.count //理解为传入state对象,修改state.count属性
  })

Here we use the ES6 arrow function to assign a value to count.

3. Assign values ​​through mapState’s array

 computed:mapState(["count"])

This is the simplest way to write it. In actual projects This is often used in development.

Mutations修改状态($store.commit( ))

Vuex提供了commit方法来修改状态,我们粘贴出Demo示例代码内容,简单回顾一下,我们在button上的修改方法。

 <button>+</button>
 <button>-</button>

store.js文件:

 const mutations={
  add(state){
   state.count+=1;
  },
  reduce(state){
   state.count-=1;
  }
 }

传值:这只是一个最简单的修改状态的操作,在实际项目中我们常常需要在修改状态时传值。比如上边的例子,是我们每次只加1,而现在我们要通过所传的值进行相加。其实我们只需要在Mutations里再加上一个参数,并在commit的时候传递就就可以了。我们来看具体代码:

现在store.js文件里给add方法加上一个参数n。

 const mutations={
  add(state,n){
   state.count+=n;
  },
  reduce(state){
   state.count-=1;
  }
 }

在Count.vue里修改按钮的commit( )方法传递的参数,我们传递10,意思就是每次加10.

 <p>
  <button>+</button>
  <button>-</button>
 </p>

模板获取Mutations方法

实际开发中我们也不喜欢看到$store.commit( )这样的方法出现,我们希望跟调用模板里的方法一样调用。
 例如:@click=”reduce” 就和没引用vuex插件一样。要达到这种写法,只需要简单的两部就可以了:

1、在模板count.vue里用import 引入我们的mapMutations:   

 import { mapState,mapMutations } from 'vuex';

2、在模板的标签里添加methods属性,并加入mapMutations

 methods:mapMutations([
   'add','reduce'
 ]),

通过上边两部,我们已经可以在模板中直接使用我们的reduce或者add方法了,就像下面这样。

 <button>-</button>

getters计算过滤操作

getters从表面是获得的意思,可以把他看作在获取数据之前进行的一种再编辑,相当于对数据的一个过滤和加工。你可以把它看作store.js的计算属性。

getters基本用法:

比如我们现在要对store.js文件中的count进行一个计算属性的操作,就是在它输出前,给它加上100.我们首先要在store.js里用const声明我们的getters属性。

 const getters = {
  count:function(state){
   return state.count +=100;
  }
 }

写好了gettters之后,我们还需要在Vuex.Store()里引入,由于之前我们已经引入了state和mutations,所以引入里有三个引入属性。代码如下,

 export default new Vuex.Store({
  state,mutations,getters
 })

在store.js里的配置算是完成了,我们需要到模板页对computed进行配置。在vue 的构造器里边只能有一个computed属性,如果你写多个,只有最后一个computed属性可用,所以要对上节课写的computed属性进行一个改造。改造时我们使用ES6中的展开运算符”…”。

 computed:{
  ...mapState(["count"]),
  count(){
   return this.$store.getters.count;
  }
 },

需要注意的是,你写了这个配置后,在每次count 的值发生变化的时候,都会进行加100的操作。

用mapGetters简化模板写法

我们都知道state和mutations都有map的引用方法把我们模板中的编码进行简化,我们的getters也是有的,我们来看一下代码。

首先用import引入我们的mapGetters

 import { mapState,mapMutations,mapGetters } from 'vuex';

在computed属性中加入mapGetters

 ...mapGetters(["count"])

actions异步修改状态

actions和之前讲的Mutations功能基本一样,不同点是,actions是异步的改变state状态,而Mutations是同步改变状态。至于什么是异步什么是同步这里我就不做太多解释了,如果你不懂自己去百度查一下吧。

在store.js中声明actions

actions是可以调用Mutations里的方法的,我们还是继续在上节课的代码基础上进行学习,在actions里调用add和reduce两个方法。

 const actions ={
  addAction(context){
   context.commit('add',10)
  },
  reduceAction({commit}){
   commit('reduce')
  }
 }

在actions里写了两个方法addAction和reduceAction,在方法体里,我们都用commit调用了Mutations里边的方法。细心的小伙伴会发现这两个方法传递的参数也不一样。

•ontext:上下文对象,这里你可以理解称store本身。
•{commit}:直接把commit对象传递过来,可以让方法体逻辑和代码更清晰明了。

模板中的使用

我们需要在count.vue模板中编写代码,让actions生效。我们先复制两个以前有的按钮,并改成我们的actions里的方法名,分别是:addAction和reduceAction。

  

       <button>-</button>   

改造一下我们的methods方法,首先还是用扩展运算符把mapMutations和mapActions加入。

  methods:{
    ...mapMutations([ 
      'add','reduce'
    ]),
    ...mapActions(['addAction','reduceAction'])
  },

你还要记得用import把我们的mapActions引入才可以使用。

增加异步检验

我们现在看的效果和我们用Mutations作的一模一样,肯定有的小伙伴会好奇,那actions有什么用,我们为了演示actions的异步功能,我们增加一个计时器(setTimeOut)延迟执行。在addAction里使用setTimeOut进行延迟执行。

  setTimeOut(()=>{context.commit(reduce)},3000);
  console.log('我比reduce提前执行');

我们可以看到在控制台先打印出了‘我比reduce提前执行'这句话。

module模块组

随着项目的复杂性增加,我们共享的状态越来越多,这时候我们就需要把我们状态的各种操作进行一个分组,分组后再进行按组编写。那今天我们就学习一下module:状态管理器的模块组操作。

声明模块组:

在vuex/store.js中声明模块组,我们还是用我们的const常量的方法声明模块组。代码如下:

  const moduleA={
    state,mutations,getters,actions
  }

声明好后,我们需要修改原来 Vuex.Stroe里的值:

  export default new Vuex.Store({
    modules:{a:moduleA}
  })

在模板中使用

现在我们要在模板中使用count状态,要用插值的形式写入。 

<h3 id="store-state-a-count">{{$store.state.a.count}}</h3>

如果想用简单的方法引入,还是要在我们的计算属性中rutrun我们的状态。写法如下:

  computed:{
    count(){
      return this.$store.state.a.count;
    }
  },

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

操作render执行有哪些方法

js实现复制文本文件功能(步奏详解)

The above is the detailed content of How to use vuex? Detailed explanation of vuex usage steps (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.