Vuex基本使用的总结--转载
在 Vue 的单页面应用中使用,需要使用Vue.use(Vuex)调用插件。
使用非常简单,只需要将其注入到Vue根实例中。
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
getter: {
doneTodos: (state, getters) => {
return state.todos.filter(todo => todo.done)
}
},
mutations: {
increment (state, payload) {
state.count++
}
},
actions: {
addCount(context) {
// 可以包含异步操作
// context 是一个与 store 实例具有相同方法和属性的 context 对象
}
}
})
// 注入到根实例
new Vue({
el: '#app',
store,
template: '<App/>',
components: { App }
})
然后改变状态:
this.$store.commit('increment')
Vuex 主要有四部分:
- state:包含了
store中存储的各个状态。 - getter: 类似于 Vue 中的计算属性,根据其他 getter 或 state 计算返回值。
- mutation: 一组方法,是改变
store中状态的执行者。 - action: 一组方法,其中可以含有异步操作。
state
Vuex 使用 state来存储应用中需要共享的状态。为了能让 Vue 组件在 state更改后也随着更改,需要基于state创建计算属性。
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count // count 为某个状态
}
}
}
getters
类似于 Vue 中的 计算属性,可以在所以来的其他 state或者 getter改变后自动改变。
每个getter方法接受 state和其他getters作为前两个参数。
getters: {
doneTodos: (state, getters) => {
return state.todos.filter(todo => todo.done)
}
}
mutations
前面两个都是状态值本身,mutations才是改变状态的执行者。mutations用于同步地更改状态
// ...
mutations: {
increment (state, n) {
state.count += n
}
}
其中,第一个参数是state,后面的其他参数是发起mutation时传入的参数。
this.$store.commit('increment', 10)
commit方法的第一个参数是要发起的mutation名称,后面的参数均当做额外数据传入mutation定义的方法中。
规范的发起mutation的方式如下:
store.commit({
type: 'increment',
amount: 10 //这是额外的参数
})
额外的参数会封装进一个对象,作为第二个参数传入mutation定义的方法中。
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
actions
想要异步地更改状态,需要使用action。action并不直接改变state,而是发起mutation。
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
发起action的方法形式和发起mutation一样,只是换了个名字dispatch。
// 以对象形式分发
store.dispatch({
type: 'incrementAsync',
amount: 10
})
action处理异步的正确使用方式
想要使用action处理异步工作很简单,只需要将异步操作放到action中执行(如上面代码中的setTimeout)。
要想在异步操作完成后继续进行相应的流程操作,有两种方式:
action返回一个promise。
而dispatch方法的本质也就是返回相应的action的执行结果。所以dispatch也返回一个promise。store.dispatch('actionA').then(() => {
// ...
})
2. 利用async/await。代码更加简洁。
// 假设 getData() 和 getOtherData() 返回的是 Promise
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
各个功能与 Vue 组件结合
将state和getter结合进组件需要使用计算属性:
computed: {
count () {
return this.$store.state.count
// 或者 return this.$store.getter.count2
}
}
将mutation和action结合进组件,需要在methods中调用this.$store.commit()或者this.$store.commit():
methods: {
changeDate () {
this.$store.commit('change');
},
changeDateAsync () {
this.$store.commit('changeAsync');
}
}
为了简便起见,Vuex 提供了四个方法用来方便的将这些功能结合进组件。
mapStatemapGettersmapMutationsmapActions
示例代码:
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
// ....
computed: {
localComputed () { /* ... */ },
...mapState({
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
count(state) {
return state.count + this.localCount
}
}),
...mapGetters({
getterCount(state, getters) {
return state.count + this.localCount
}
})
}
methods: {
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为`this.$store.commit('increment')`
}),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
如果结合进组件之后不想改变名字,可以直接使用数组的方式。
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
}
将 store分割为模块。
可以将应用的store分割为小模块,每个模块也都拥有所有的东西:state, getters, mutations, actions。
首先创建子模块的文件:
// initial state
const state = {
added: [],
checkoutStatus: null
}
// getters
const getters = {
checkoutStatus: state => state.checkoutStatus
}
// actions
const actions = {
checkout ({ commit, state }, products) {
}
}
// mutations
const mutations = {
mutation1 (state, { id }) {
}
}
export default {
state,
getters,
actions,
mutations
}
然后在总模块中引入:
import Vuex from 'vuex'
import products from './modules/products' //引入子模块 Vue.use(Vuex)
export default new Vuex.Store({
modules: {
products // 添加进模块中
}
})
其实还存在命名空间的概念,大型应用会使用。需要时查看文档即可。Vuex的基本使用大致如此。
作者:胡不归vac
链接:https://www.jianshu.com/p/aae7fee46c36
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Vuex基本使用的总结--转载的更多相关文章
- vue-cli3 vue.config.js 配置
// cli_api配置地址 https://cli.vuejs.org/zh/config/ module.exports = { baseUrl: './', // 部署应用包时的基本 URL o ...
- vuex 、store、state (转载)
vuex 文档 https://vuex.vuejs.org/zh/guide/state.html
- vuex简介(转载)
安装.使用 vuex 首先我们在 vue.js 2.0 开发环境中安装 vuex : npm install vuex --save 然后 , 在 main.js 中加入 : import vuex ...
- 前端 vue单页面应用刷新网页后vuex的state数据丢失的解决方案(转载)
最近接手了一个项目,前端后端都要做,之前一直在做服务端的语言.框架和环境,前端啥都不会啊. 突然需要前端编程,两天速成了JS和VUE框架,可惜还是个半吊子.然后遇到了一个困扰了一整天的问题.一直调试都 ...
- Vuex源码解析
写在前面 因为对Vue.js很感兴趣,而且平时工作的技术栈也是Vue.js,这几个月花了些时间研究学习了一下Vue.js源码,并做了总结与输出. 文章的原地址:https://github.com/a ...
- 【前端】Vue2全家桶案例《看漫画》之三、引入vuex
转载请注明出处:http://www.cnblogs.com/shamoyuu/p/vue_vux_app_3.html 项目github地址:https://github.com/shamoyuu/ ...
- Vue—组件传值及vuex的使用
一.父子组件之间的传值 1.父组件向子组件传值: 子组件在props中创建一个属性,用以接收父组件传来的值 父组件中注册子组件 在子组件标签中添加子组件props中创建的属性 把需要传给子组件的值赋给 ...
- vue单页面应用刷新网页后vuex的state数据丢失的解决方案
1. 产生原因其实很简单,因为store里的数据是保存在运行内存中的,当页面刷新时,页面会重新加载vue实例,store里面的数据就会被重新赋值. 2. 解决思路一种是state里的数据全部是通过请求 ...
- 2、vuex页面刷新数据不保留,解决方法(转)
今天这个问题又跟页面的刷新有一定的关系,虽然说跟页面刷新的关系不大,但确实页面刷新引起的这一个问题. 场景: VueX里存储了 this.$store.state.PV这样一个变量,这个变量是在app ...
随机推荐
- JAVA CST时间 转换成Date
Mybatis中处理Oracle时间类型是个比较麻烦的问题,特别是需要用到时间做比较的,可参考以下代码与思路: 格式化CST时间 SimpleDateFormat sdf = new SimpleDa ...
- MarkDown富文本编辑器怎么加载模板文件
我们只需要一段加载代码就可以搞定MarkDown加载模板文件. $("#md-demo").bind('click', function () { $.get("/Lib ...
- Python的6种内建序列之通用操作
数据结构式通过某种方式(例如对元素进行编号)组织在一起的数据元素的集合,这些数据元素可以是数字或者字符,甚至可以是其他数据结构.在Python中,最基本的数据结构是序列(sequence).序列中的每 ...
- Ubuntu Server中怎样卸载keepalived
场景 在Ubuntu Server中进行安装keepalived ,如果安装过程中出现纰漏,想要重新安装keepalived或者就是想直接卸载keepalived. 我们在安装keepalived时指 ...
- SSM框架之Spring(3)IOC及依赖注入(基于注解的实现)
Spring(3)IOC及依赖注入(基于注解的实现) 学习基于注解的 IoC 配置,大家脑海里首先得有一个认知,即注解配置和 xml 配置要实现的功能都是一样 的,都是要降低程序间的耦合.只是配置的形 ...
- Thymeleaf常用语法:表达式语法之运算符
Thymeleaf表达式语法之常量分为字符串常量.数字常量.布尔值常量.空值常量:运算符分为算术运算符.关系运算符.条件运算符.无操作符. 开发环境:IntelliJ IDEA 2019.2.2Spr ...
- SQL Server查询数据库表字段类型
select b.name,a.name,c.name,a.xprec,a.xscalefrom syscolumns aleft outer join sysobjects b ON a.id=b ...
- 如何快速查看 group 对应的id
最近需要获取group 对应的id 数字号码,突然想不起来怎么获得了,现在在这里进行备忘一下: $ cut -d: -f3 < <(getent group sudo) getent gr ...
- Linux—挂载磁盘(云盘)
创建挂载目录 [root@localhost ~]# mkdir -p /www 可以看到/dev/vda1盘挂载/ /dev都是位于根路径下,都属于系统盘.根路径 / 都是位于系统盘.而/root, ...
- [Linux] Nginx服务下统计网站的QPS
单位时间的请求数就是QPS,那么在nginx服务的网站下,如果要统计QPS并且按从高到低排列,需要使用awk配合sort进行处理awk做的主要工作是把access每行日志按分隔符分开,然后循环每一行, ...