Vuex from scratch

php中世界最好的语言
Release: 2018-06-08 11:19:38
Original
1040 people have browsed it

This time I will bring you Vuex from scratch. What are the precautions for starting Vuex from scratch? 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
Copy after login

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';
Copy after login
Copy after login

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

import Vue from 'vue'; import Vuex from 'vuex';
Copy after login
Copy after login

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'
Copy after login

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

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

Come on as a fledgling 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 }
Copy after login

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

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

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.

 
Copy after login

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

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

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.

Copy after login

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 .

Assign the learning status object to the internal object, that is, assign the value in stoe.js 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; } }
Copy after login

What needs to be noted here is thatreturn this.$store.state.countThis sentence must be written, 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';
Copy after login

Then write the following code in the computed property:

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

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

3. Assign values through the mapState array

computed:mapState(["count"])
Copy after login

This is the simplest way to write, and it is often used in actual project development. .

Mutations修改状态($store.commit( ))
Copy after login

Vuex provides the commit method to modify the state. We paste the Demo sample code content and briefly review our modification method on the button.

 
Copy after login

store.js file:

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

Passing value: This is just the simplest operation to modify the state. In actual projects, we often need to pass the value when modifying the state. For example, in the above example, we only add 1 each time, but now we need to add the values passed. In fact, we only need to add another parameter to Mutations and pass it when committing. Let’s look at the specific code:

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

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

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

Copy after login

模板获取Mutations方法

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

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

import { mapState,mapMutations } from 'vuex';
Copy after login

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

methods:mapMutations([ 'add','reduce' ]),
Copy after login

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

Copy after login

getters计算过滤操作

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

getters基本用法:

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

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

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

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

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

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

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

用mapGetters简化模板写法

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

首先用import引入我们的mapGetters

import { mapState,mapMutations,mapGetters } from 'vuex';
Copy after login

在computed属性中加入mapGetters

...mapGetters(["count"])
Copy after login

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') } }
Copy after login

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

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

模板中的使用

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

Copy after login

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

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

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

增加异步检验

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

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

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

module模块组

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

声明模块组:

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

const moduleA={ state,mutations,getters,actions }
Copy after login

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

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

在模板中使用

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

{{$store.state.a.count}}

Copy after login

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

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

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

推荐阅读:

sort如何进行son数据排序

怎样操作日历范围选择插件

The above is the detailed content of Vuex from scratch. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!