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? 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 '@/vuex/store' export default{ data(){ return{ msg:'Hello Vuex', } }, 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中文网其它相关文章!
推荐阅读:
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!

Vue2.x是目前最流行的前端框架之一,它提供了Vuex作为管理全局状态的解决方案。使用Vuex能够使得状态管理更加清晰、易于维护,下面将介绍Vuex的最佳实践,帮助开发者更好地使用Vuex以及提高代码质量。1.使用模块化组织状态Vuex使用单一状态树管理应用的全部状态,将状态从组件中抽离出来,使得状态管理更加清晰易懂。在具有较多状态的应用中,必须使用模块
![在Vue应用中使用vuex时出现“Error: [vuex] do not mutate vuex store state outside mutation handlers.”怎么解决?](https://img.php.cn/upload/article/000/000/164/168760467048976.jpg)
在Vue应用中,使用vuex是常见的状态管理方式。然而,在使用vuex时,我们有时可能会遇到这样的错误提示:“Error:[vuex]donotmutatevuexstorestateoutsidemutationhandlers.”这个错误提示是什么意思呢?为什么会出现这个错误提示?如何解决这个错误?本文将详细介绍这个问题。错误提示的含

Vuex是做什么的?Vue官方:状态管理工具状态管理是什么?需要在多个组件中共享的状态、且是响应式的、一个变,全都改变。例如一些全局要用的的状态信息:用户登录状态、用户名称、地理位置信息、购物车中商品、等等这时候我们就需要这么一个工具来进行全局的状态管理,Vuex就是这样的一个工具。单页面的状态管理View–>Actions—>State视图层(view)触发操作(action)更改状态(state)响应回视图层(view)vuex(Vue3.
![在Vue应用中使用vuex时出现“Error: [vuex] unknown action type: xxx”怎么解决?](https://img.php.cn/upload/article/000/887/227/168766615217161.jpg)
在Vue.js项目中,vuex是一个非常有用的状态管理工具。它可以帮助我们在多个组件之间共享状态,并提供了一种可靠的方式来管理状态的变化。但在使用vuex时,有时会遇到“Error:[vuex]unknownactiontype:xxx”的错误。这篇文章将介绍该错误的原因及解决方法。1.错误原因在使用vuex时,我们需要定义一些actions和mu

在Vue应用的开发过程中,使用vuex来管理应用状态是非常常见的做法。然而,在使用vuex的过程中,有时我们可能会遇到这样的错误提示:“Error:'xxx'hasalreadybeendeclaredasadataproperty.”这个错误提示看起来很莫名其妙,但其实是由于在Vue组件中,使用了重复的变量名来定义data属性和vuex

在Vue应用中使用Vuex是非常常见的操作。然而,偶尔在使用Vuex时会遇到错误信息“TypeError:Cannotreadproperty'xxx'ofundefined”,这个错误信息的意思是无法读取undefined的属性“xxx”,导致了程序的错误。这个问题其实产生的原因很明显,就是因为在调用Vuex的某个属性的时候,这个属性没有被正确

具体步骤:1、安装vuex(vue3建议4.0+)pnpmivuex-S2、main.js中配置importstorefrom'@/store'//hx-app的全局配置constapp=createApp(App)app.use(store)3、新建相关的文件夹与文件,这里配置多个不同vuex内部的js,使用vuex的modules来放不同的页面,文件,然后统一使用一个getters.jsindex.js核心文件,这里使用了import.meta.glob,而不


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version

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.

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!
