vuex的使用

北城以北 提交于 2019-12-02 00:09:50

1 vuex 的安装和使用

安装vuex npm i –S vuex  => 运行时依赖

导入vue模块和vuex模块

image

安装vuex模块

image

创建vuex实例store

image

导出vuex模块   export default store

main.js中引用vuex模块 

import store from './store/index.js'

image

实例对象中有5个属性 ====vuex数据流程图如下

image

state属性用来保存数据,mutations属性用来对state中的数据进行修改并保存

action负责异步操作数据(mutations是同步的),getters类似computed属性

负责返回一个计算结果,modules负责控制vuex模块

state

定义

image

使用

image

mutations

通过mutations改state 只允许同步操作,devtools只能追踪同步代码来保存更改记录

image

使用

image

image


mutations常量使用:抽取方法名

image

image

moutations-types.js

image

参数传递 默认传递state参数

image

传递自定义参数

直接传递

image

对象传递

image

使用

html上

image

js上

image

mutations的响应式 ==> 改变对象和数组 Vue.set()  Vue.delete()

image

actions

异步请求操作必须通过actions 再调用mutations里的方法来改变数据

image

默认参数contxt,contxt是上下文的意思,这里指store,允许传自定义参数

使用

image

image

getters

image

默认参数state ,类似computed必须有返回值


getters中的方法可以通过传入getters参数来获取其他getters方法的返回值

image

getters允许传入state和getters,不允许传入自定义参数,若想在使用getters时传自定义参数,可以通过返回函数

image

使用

image


modules

image

moduleA 的定义

image

注意点:

getters上有一个rootState参数,表示store实例中的state

使用

image

image

除了state属性的引用需要加上module名外,其他与先前store实例中一样

因此module的getters,actions,mutations中方法名要避免与store中的重复

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!