In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what are the differences between vue-resource and vuex". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
The difference between vue-resource and vuex: 1, vue-resource is a plug-in for processing HTTP requests, while Vuex is a state management library developed specifically for Vue.js applications; 2, developed from Vue2.0, vue-resource is no longer updated, while vuex continues to update.
The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.
Introduction to vue-resource
Vue-resource is a very lightweight plug-in for processing HTTP requests. After Vue2.0, vue-resource is no longer updated, but axios is recommended.
Features:
Small size: vue-resource is very small, only about 12kb after compression, and only 4.5kb size when gzip compression is enabled on the server.
Support for mainstream browsers: all major browsers support it except for IE browsers after IE9.
Support for Promise API and URI Templates:Promise is a feature of ES6 and is used for asynchronous computing; URI Templates represents a URI template, somewhat similar to ASP.NET.MVC 's routing template.
Support interceptor: interceptor is global, interceptor can do some processing before and after the request is sent.
Introduction to vuex
Vuex is a state management library developed specifically for Vue.js applications. It uses centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable way. Vuex is also integrated into Vue's official debugging tool devtools extension, providing advanced debugging features such as zero configuration time-travel debugging, status snapshot import and export, and so on.
This status self-management application consists of the following parts:
State, the data source that drives the application
View, declaratively mapping state to views
Actions, responding to state changes caused by user input on the view.
In a Vue project with VueX, we only need to define these values in the VueX to be used in the components of the entire Vue project.
1. Installation
Since VueX is done after learning VueCli, please refer to the directory built by VueCli 2.x for the project directory that appears below.
The premise of the following steps is that you have completed the construction of the Vue project and have been transferred to the project's file directory.
Npm install Vuex
Npm i vuex-s
Add a new store folder under the root of the project, and create an index.js within that folder
At this point the src folder of your project should look like this
│ App.vue │ main.js │├─ assets │ logo.png │├─ components │ HelloWorld.vue │├─ router │ index.js │└─ store index.js2 、 Initialize the contents in index.js under store import Vue from 'vue'import Vuex from' vuex'// mount VuexVue.use (Vuex) / / create a VueX object const store = new Vuex.Store ({state: {/ / the key-value pair stored is the state name:'helloVueX'}} to be managed) export default store
2.2 Mount store to the Vue instance of the current project
Open main.js
Import Vue from 'vue'import App from'. / App'import router from'. / router'import store from'. / store'Vue.config.productionTip = false/* eslint-disable no-new * / new Vue ({el:'# app', router, store, / / store:store, like router, mount the Vuex instance we created to this vue instance render: h = > h (App)})
2.3 using Vuex in components
For example, in App.vue, we want to display the name defined in state in the H2 tag
Name: {{$store.state.name}}
Or to use in a component method
, methods: {add () {console.log (this.$store.state.name)}},...
Note that do not change the value of the state in state here, which will be described later
3. Install the Vue development tool VueDevtools
In the development of Vue project, various values in the project need to be monitored. In order to improve efficiency, Vue provides a browser extension-VueDevtools.
When learning VueX, you need to use this plug-in even more. About the use of the plug-in can be moved to the official website, I will not repeat it here.
The core content of VueX
In the VueX object, there are not only state, but also the set of methods used to manipulate the data in state, and the set of methods that need to be processed when we need to process the data in state.
Member list:
State storage status
Mutations state member operation
Getters processes state members to the outside world
Actions asynchronous operation
Modules Modular State Management
The workflow of VueX
Flow chart given on Vuex's official website
First of all, if the Vue component needs to request from the backend during the process of calling a method of a VueX, or when an asynchronous operation occurs, it needs the method of actions in dispatch VueX to ensure the synchronization of the data. It can be said that action exists to make the methods in mutations work in asynchronous operations.
If there is no asynchronous operation, we can directly implement the operation on the state member in the method written by ourselves in the Mutations in the state of the submission in the component. Note that as mentioned in Section 1.3.3, it is not recommended to operate directly on members of the state in the component, because direct modifications (for example, this.$store.state.name = 'hello') cannot be monitored by VueDevtools.
Finally, the modified state member will be rendered to the original location of the component.
2 Mutations
A mutations is a collection of methods that manipulate state data, such as modifications, additions, deletions, and so on.
2.1 how to use Mutations
All mutations methods have default formal parameters:
([state] [, payload])
State is the state in the current VueX object
Payload is used by this method to pass parameters when called
For example, we write a method that, when executed, can change the name value in the following example to "jack". We just need to do this.
Index.js
Import Vue from 'vue'import Vuex from' vuex'Vue.use (Vuex) const store = new Vuex.store ({state: {name:'helloVueX'}, mutations: {/ / es6 syntax, equivalent to edit:funcion () {...} edit (state) {state.name = 'jack'}) export default store
In the component, we need to call the mutation-- like this, for example, in a method in App.vue:
This.$store.commit ('edit') 2.2 Mutation passes a value
In the actual production process, you will encounter that you need to bring some parameters to the method when submitting a mutation.
When a single value is submitted:
This.$store.commit ('edit',15)
When multiple parameters are needed to submit, it is recommended to put them in an object to submit:
This.$store.commit ('edit', {age:15,sex:' male'})
Receive mount parameters:
Edit (state,payload) {state.name = 'jack' console.log (payload) / / 15 or {age:15,sex:' Man'}}
Another way to submit
This.$store.commit ({type:'edit', payload: {age:15, sex:' Man'}}) 2.3 add and delete members in state
In order to match the responsive data of Vue, we should use the method provided by Vue to operate in the method of Mutations. If you delete or add in the form of delete or xx.xx = xx, Vue cannot respond to the data in real time.
Vue.set sets the value of a member for an object. If it does not exist, add
For example, add an age member to the state object
Vue.set (state, "age", 15)
Vue.delete Delete member
Delete the age member you just added
Vue.delete (state,'age') 3 Getters
The members in state can be processed and passed to the outside world.
Methods in Getters have two default parameters
State objects in the current VueX object of state
Getters current getters object, which is used to bring other getter under getters to use.
For example
Getters: {nameInfo (state) {return "name:" + state.name}, fullInfo (state,getters) {return getters.nameInfo+' Age:'+ state.age}}
Called in the component
This.$store.getters.fullInfo4 Actions
Data invalidation will be caused by performing asynchronous operations directly in the mutation method. So Actions is provided to specialize in asynchronous operations, resulting in the submission of mutation methods.
Methods in Actions have two default parameters
Context context (equivalent to this in the arrow function) object
Payload mount parameters
For example, we execute the edit method in Section 2.2.2 after two seconds
Because setTimeout is an asynchronous operation, actions is required
Actions: {aEdit (context,payload) {setTimeout (()) = > {context.commit ('edit',payload)}, 2000)}}
Call in the component:
This.$store.dispatch ('aEdit', {age:15})
Improvements:
Because it is an asynchronous operation, we can encapsulate it as a Promise object for our asynchronous operation
AEdit (context,payload) {return new Promise ((resolve,reject) = > {setTimeout () = > {context.commit ('edit',payload) resolve ()}, 2000)} 5 modules
When the project is large and has a lot of states, the modular management mode can be adopted. Vuex allows us to split store into modules (module). Each module has its own state, mutation, action, getter, and even nested submodules-- segmented in the same way from top to bottom.
Modules: {a: {state: {}, getters: {},.... }}
The status of the calling module a within the component:
This.$store.state.a
As before, a method of submitting or dispatch automatically executes the corresponding type methods in all modules:
Details of this.$store.commit ('editKey') this.$store.dispatch (' aEditKey') 5.1module
The first parameter accepted by the methods in mutations and getters in the module is the state within its own local module.
Modules: {a: {state: {key:5}, mutations: {editKey (state) {state.key = 9}},.... }}
The third parameter of the method in getters is the root node state.
Modules: {a: {state: {key:5}, getters: {getKeyCount (state,getter,rootState) {return rootState.key + state.key}},.... }}
The method in actions gets the local module state is context.state, and the root node state is context.rootState
Modules: {a: {state: {key:5}, actions: {aEidtKey (context) {if (context.state.key = context.rootState.key) {context.commit ('editKey')},.... }} standardize the directory structure
It is unreasonable to put the entire store in the index.js, so it needs to be split. The more appropriate directory format is as follows:
Store:. │ actions.js │ getters.js │ index.js │ mutations.js │ mutations_type.js # # this is a file that stores mutaions method constants. You can add │└─ modules Astore.js as needed.
The corresponding content is stored in the corresponding file, and the store is stored and exported in index.js as before. The data in state is kept in index.js as much as possible. The Astore local module state in modules can also be subdivided if there are many.
This is the end of the content of "what are the differences between vue-resource and vuex". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.