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 specially developed for Vue.js applications; 2. From Vue2 .0 development, vue-resource is no longer updated, but vuex continues to be updated.
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 will no longer be updated, but axios is recommended.
Features:
Small size: vue-resource is very small, only about 12kb after compression, and only 4.5 after enabling gzip compression on the server kb size.
Supports mainstream browsers: Except for IE browsers after IE9, which are not supported, other mainstream browsers are supported.
Support Promise API and URI Templates: Promise is a feature of ES6, used for asynchronous calculation; URI Templates represent URI templates, some similar to ASP.NET.MVC routing templates.
Support interceptors: Interceptors are global and 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, which provides advanced debugging functions such as zero-configuration time-travel debugging, status snapshot import and export, etc.
This state self-management application includes the following parts:
state, the data source that drives the application;
view, declaratively maps state to the view;
actions, responds to state changes caused by user input on the view.
In a Vue project with VueX, we only need to define these values in VueX to use them in components of the entire Vue project.
1. Installation
Since VueX
is done after learning VueCli
, the items that appear below are For the directory, please refer to the directory built by VueCli 2.x
.
The following steps assume that you have completed building the Vue project and have moved to the file directory of the project.
-
Npm install Vuex
npm i vuex -s
-
Create a new
store
folder in the root directory of the project, in this file Create index.js in the folderAt this time, the
src
folder of your project should be like this│ App.vue │ main.js │ ├─assets │ logo.png │ ├─components │ HelloWorld.vue │ ├─router │ index.js │ └─store index.js
2. Use
2.1 Initialize the content in index.js
under store
import Vue from 'vue' import Vuex from 'vuex' //挂载Vuex Vue.use(Vuex) //创建VueX对象 const store = new Vuex.Store({ state:{ //存放的键值对就是所要管理的状态 name:'helloVueX' } }) export default store
2.2 Initialize the store Mount 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 和router一样,将我们创建的Vuex实例挂载到这个vue实例中 render: h => h(App) })
2.3 Use Vuex in the component
For example, in In App.vue, we need to use the name defined in the state to display
<template> <div id='app'> name: <h1 id="nbsp-store-state-name-nbsp">{{ $store.state.name }}</h1> </div> </template>
in the h1 tag or use
..., methods:{ add(){ console.log(this.$store.state.name) } }, ...
in the component method. Note, please do not use this Change the value of the state in state
, which will be explained later
3. Install the Vue development tool VueDevtools
in Vue During project development, it is necessary to monitor various values in the project. In order to improve efficiency, Vue provides a browser extension - VueDevtools.

在学习VueX时,更为需要使用该插件。关于该插件的使用可以移步官网,在此不再赘叙。
VueX中的核心内容
在VueX对象中,其实不止有state
,还有用来操作state
中数据的方法集,以及当我们需要对state
中的数据需要加工的方法集等等成员。
成员列表:
- state 存放状态
- mutations state成员操作
- getters 加工state成员给外界
- actions 异步操作
- modules 模块化状态管理
VueX的工作流程
Vuex官网给出的流程图
首先,Vue
组件如果调用某个VueX
的方法过程中需要向后端请求时或者说出现异步操作时,需要dispatch
VueX中actions
的方法,以保证数据的同步。可以说,action
的存在就是为了让mutations
中的方法能在异步操作中起作用。
如果没有异步操作,那么我们就可以直接在组件内提交状态中的Mutations
中自己编写的方法来达成对state
成员的操作。注意,1.3.3节
中有提到,不建议在组件中直接对state
中的成员进行操作,这是因为直接修改(例如:this.$store.state.name = 'hello'
)的话不能被VueDevtools
所监控到。
最后被修改后的state成员会被渲染到组件的原位置当中去。
2 Mutations
mutations
是操作state
数据的方法的集合,比如对该数据的修改、增加、删除等等。
2.1 Mutations使用方法
mutations
方法都有默认的形参:
([state] [,payload])
-
state
是当前VueX
对象中的state
-
payload
是该方法在被调用时传递参数使用的
例如,我们编写一个方法,当被执行时,能把下例中的name值修改为"jack"
,我们只需要这样做
index.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.store({ state:{ name:'helloVueX' }, mutations:{ //es6语法,等同edit:funcion(){...} edit(state){ state.name = 'jack' } } }) export default store
而在组件中,我们需要这样去调用这个mutation
——例如在App.vue的某个method
中:
this.$store.commit('edit')
2.2 Mutation传值
在实际生产过程中,会遇到需要在提交某个mutation
时需要携带一些参数给方法使用。
单个值提交时:
this.$store.commit('edit',15)
当需要多参提交时,推荐把他们放在一个对象中来提交:
this.$store.commit('edit',{age:15,sex:'男'})
接收挂载的参数:
edit(state,payload){ state.name = 'jack' console.log(payload) // 15或{age:15,sex:'男'} }
另一种提交方式
this.$store.commit({ type:'edit', payload:{ age:15, sex:'男' } })
2.3 增删state中的成员
为了配合Vue的响应式数据,我们在Mutations的方法中,应当使用Vue提供的方法来进行操作。如果使用delete
或者xx.xx = xx
的形式去删或增,则Vue不能对数据进行实时响应。
Vue.set 为某个对象设置成员的值,若不存在则新增
例如对state对象中添加一个age成员
Vue.set(state,"age",15)
Vue.delete 删除成员
将刚刚添加的age成员删除
Vue.delete(state,'age')
3 Getters
可以对state中的成员加工后传递给外界
Getters中的方法有两个默认参数
- state 当前VueX对象中的状态对象
- getters 当前getters对象,用于将getters下的其他getter拿来用
例如
getters:{ nameInfo(state){ return "姓名:"+state.name }, fullInfo(state,getters){ return getters.nameInfo+'年龄:'+state.age } }
组件中调用
this.$store.getters.fullInfo
4 Actions
由于直接在mutation
方法中进行异步操作,将会引起数据失效。所以提供了Actions来专门进行异步操作,最终提交mutation
方法。
Actions
中的方法有两个默认参数
-
context
上下文(相当于箭头函数中的this)对象 -
payload
挂载参数
例如,我们在两秒中后执行2.2.2
节中的edit
方法
由于setTimeout
是异步操作,所以需要使用actions
actions:{ aEdit(context,payload){ setTimeout(()=>{ context.commit('edit',payload) },2000) } }
在组件中调用:
this.$store.dispatch('aEdit',{age:15})
改进:
由于是异步操作,所以我们可以为我们的异步操作封装为一个Promise
对象
aEdit(context,payload){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ context.commit('edit',payload) resolve() },2000) }) }
5 modules
当项目庞大,状态非常多时,可以采用模块化管理模式。Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter
、甚至是嵌套子模块——从上至下进行同样方式的分割。
modules:{ a:{ state:{}, getters:{}, .... } }
组件内调用模块a的状态:
this.$store.state.a
而提交或者dispatch
某个方法和以前一样,会自动执行所有模块内的对应type
的方法:
this.$store.commit('editKey') this.$store.dispatch('aEditKey')
5.1 模块的细节
模块中mutations
和getters
中的方法接受的第一个参数是自身局部模块内部的state
modules:{ a:{ state:{key:5}, mutations:{ editKey(state){ state.key = 9 } }, .... }}
getters
中方法的第三个参数是根节点状态
modules:{ a:{ state:{key:5}, getters:{ getKeyCount(state,getter,rootState){ return rootState.key + state.key } }, .... } }
actions
中方法获取局部模块状态是context.state
,根节点状态是context.rootState
modules:{ a:{ state:{key:5}, actions:{ aEidtKey(context){ if(context.state.key === context.rootState.key){ context.commit('editKey') } } }, .... } }
规范目录结构
如果把整个store
都放在index.js
中是不合理的,所以需要拆分。比较合适的目录格式如下:
store:. │ actions.js │ getters.js │ index.js │ mutations.js │ mutations_type.js ##该项为存放mutaions方法常量的文件,按需要可加入 │ └─modules Astore.js
对应的内容存放在对应的文件中,和以前一样,在index.js
中存放并导出store
。state
中的数据尽量放在index.js
中。而modules
中的Astore
局部模块状态如果多的话也可以进行细分。
【相关推荐:vue.js教程】
The above is the detailed content of What is the difference between vue-resource and vuex. For more information, please follow other related articles on the PHP Chinese website!

HTML and React can be seamlessly integrated through JSX to build an efficient user interface. 1) Embed HTML elements using JSX, 2) Optimize rendering performance using virtual DOM, 3) Manage and render HTML structures through componentization. This integration method is not only intuitive, but also improves application performance.

React efficiently renders data through state and props, and handles user events through the synthesis event system. 1) Use useState to manage state, such as the counter example. 2) Event processing is implemented by adding functions in JSX, such as button clicks. 3) The key attribute is required to render the list, such as the TodoList component. 4) For form processing, useState and e.preventDefault(), such as Form components.

React interacts with the server through HTTP requests to obtain, send, update and delete data. 1) User operation triggers events, 2) Initiate HTTP requests, 3) Process server responses, 4) Update component status and re-render.

React is a JavaScript library for building user interfaces that improves efficiency through component development and virtual DOM. 1. Components and JSX: Use JSX syntax to define components to enhance code intuitiveness and quality. 2. Virtual DOM and Rendering: Optimize rendering performance through virtual DOM and diff algorithms. 3. State management and Hooks: Hooks such as useState and useEffect simplify state management and side effects handling. 4. Example of usage: From basic forms to advanced global state management, use the ContextAPI. 5. Common errors and debugging: Avoid improper state management and component update problems, and use ReactDevTools to debug. 6. Performance optimization and optimality

Reactisafrontendlibrary,focusedonbuildinguserinterfaces.ItmanagesUIstateandupdatesefficientlyusingavirtualDOM,andinteractswithbackendservicesviaAPIsfordatahandling,butdoesnotprocessorstoredataitself.

React can be embedded in HTML to enhance or completely rewrite traditional HTML pages. 1) The basic steps to using React include adding a root div in HTML and rendering the React component via ReactDOM.render(). 2) More advanced applications include using useState to manage state and implement complex UI interactions such as counters and to-do lists. 3) Optimization and best practices include code segmentation, lazy loading and using React.memo and useMemo to improve performance. Through these methods, developers can leverage the power of React to build dynamic and responsive user interfaces.

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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.