Vue系列二十六:vuex-案例
2019-05-19 14:17
337 查看
1、映射 store。main.js
import Vue from 'vue' import App from './components/App.vue' import store from './store' new Vue({ el: '#app', render: h => h(App), //渲染函数 store })
2、状态对象。state.js
//状态对象 const state = {//初始化状态 count: 0 }
3、包含多个由action触发直接更新状态的方法的对象。mutations.js
//包含多个更新state函数的对象 const mutations = { //增加的mutation INCREMENT(state){ state.count++ }, //减少的mutation DECREMENT(state){ state.count-- }, }
4、包含多个对应事件回调函数的对象。actions.js
//包含多个对应事件回调函数的对象 const actions = { //增加的action increment({commit}){ //提交增加的mutation commit('INCREMENT') }, //减少的action decrement({commit}){ //提交减少的mutation commit('DECREMENT') }, //带条件的action incrementIfOdd({commit,state}){ if(state.count%2===1){ //提交增加的mutation commit('INCREMENT') } }, //异步的action incrementAsync({commit}){ //在action中直接就可以执行异步代码 setTimeout(() => { //提交增加的mutation commit('INCREMENT') },1000) } }
5、包含多个getter计算属性函数的对象。getters.js
//包含多个getter计算属性函数的对象 const getters = { evenOrOdd(state){ //不需要调用,只需要读取属性值 return state.count%2===0?'偶数':'奇数' } }
6、vuex最核心的管理对象store。index.js
import Vue from 'vue' import Vuex from 'vuex' import state from './state' import mutations from './mutations' import actions from './actions' import getters from './getters' Vue.use(Vuex) export default new Vuex.Store({ state, mutations, actions, getters })
在组件中使用。
...mapActions([ '你要获取的actions名字' ]),你传入什么,就会返回一个包含对应的actions的对象,通过
...对象扩展运算符,将返回值解析就成为methods的属性,和平常的方法一样调用即可。
<template> <div> <p>click {{count}} times,count is {{evenOrOdd}}</p> <button @click="increment">+</button> <button @click="decrement">-</button> <button @click="incrementIfOdd">increment if odd</button> <button @click="incrementAsync">increment async</button> </div> </template> <script> import {mapState,mapGetters,mapActions} from 'vuex' export default { computed:{ ...mapState(['count']),//mapGetters()返回值对象:{count(){return this.$store.state['count']}} ...mapGetters({evenOrOdd: 'evenOrOdd2'}),//mapGetters()返回值对象:{evenOrOdd(){return this.$store.getters['evenOrOdd']}} }, methods:{ ...mapActions(['increment','decrement','incrementIfOdd','incrementAsync']) } } </script>
相关文章推荐
- Vue.js学习系列(二十六)-- 循环语句(二)
- vue 2.0系列QQ音乐播放器案例
- vue系列——vue-resources入门案例
- vue系列之flex经典案例
- DBA_实践指南系列4_Oracle Erp R12系统备份和恢复Backup(案例)
- Smart3D系列教程4之 《案例实战演练1——小物件的照片三维重建》
- DBA_实践指南系列10_Oracle Erp R12诊断功能Diagnostic(案例)
- JavaScript - Vue经典教程系列-李游Leo-专题视频课程
- Vue.js学习系列三——axios和网络传输相关知识的学习实践
- Vue入门系列之Vue实例详解与生命周期
- 大型网站架构系列:电商网站架构案例(3)
- [jQuery学习系列六]6-jQuery实际操作小案例
- vue踩坑系列——backgroundImage路径问题
- 第一章:重构,第一个案例(读书笔记系列2)
- vue系列---三元表达式和if进行页面的切换
- Vue.js学习系列(三十三)-- Vue.js样式绑定(四)
- Vue系列:通过vue-router如何传递参数
- 2018最新Vue.js + Node.js实现音乐播放器实战案例
- [MySQL优化案例]系列 — 典型性索引引发CPU负载飙升问题
- [MySQL优化案例]系列 -- 频繁创建临时表