1.插件

下面以一个对state进行持久化存储的插件为例进行介绍:

代码结构:

saveInLocal.js

  1. export default function (store) {
  2. if (localStorage.state) {
  3. store.replaceState(JSON.parse(localStorage.state));
  4. }
  5. store.subscribe((mutation, state) => {
  6. //在HTML5中,新加入了一个localStorage特性,这个特性主要是用来作为本地存储来使用的,解决了cookie存储空间不足的问题(cookie中每条cookie的存储空间为4k),localStorage中一般浏览器支持的是5M大小,这个在不同的浏览器中localStorage会有所不同。
  7. localStorage.state = JSON.stringify(state);
  8. });
  9. }

index.js

  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. import state from "./state"
  4. import getters from './getters'
  5. import mutations from "./mutations"
  6. import actions from "./actions"
  7. import user from './module/user'
  8. import saveInLocal from './plugin/saveInLocal';
  9.  
  10. Vue.use(Vuex)
  11.  
  12. export default new Vuex.Store({
  13. state,
  14. getters,
  15. mutations,
  16. actions,
  17. modules: {
  18. user
  19. },
  20. plugins:[saveInLocal]
  21. })

store.vue:

  1. <template>
  2. <div>
  3. <a-input :value="inputValue" @input="handlerInput"></a-input>
  4. <p>{{ inputValue }} -> lastLetter is {{ inputValueLastLetter }}</p>
  5. <p>appName: {{ appName }}, appNameWithVersion : {{ appNameWithVersion }}</p>
  6. <p>userName : {{ userName }}, firstLetter is : {{ firstLetter }}</p>
  7. <button @click="handleChangeAppName">修改appName和user.js中的userName</button>
  8. <p>动态给state增加appVersion: {{ appVersion }}</p>
  9. <button @click="handleActionChangeAppName">通过Action修改appName</button>
  10. <button @click="registerModule">动态注册模块</button>
  11. <p v-for="(li, index) in todoList" :key="index">{{ li }}</p>
  12. </div>
  13. </template>
  14. <script>
  15. import AInput from "_c/AInput.vue";
  16. import AShow from "_c/AShow.vue";
  17. //变量的解构赋值
  18. import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
  19. import { stat } from "fs";
  20. export default {
  21. name: "store",
  22. data() {
  23. return {
  24. inputValue: ""
  25. };
  26. },
  27. components: {
  28. AInput: AInput,
  29. AShow: AShow
  30. },
  31. computed: {
  32. //ES6展开操作符 mapState展开会形成一个对象 使用对象展开运算符将此对象混入到外部对象中
  33. ...mapState({
  34. appName: state => state.appName,
  35. appVersion: state => state.appVersion,
  36. userName: state => state.user.userName,
  37. todoList: state => (state.user.todo ? state.user.todo.todoList : [])
  38. }),
  39. // 使用对象展开运算符将 getter 混入 computed 对象中
  40. // ...mapGetters(["appNameWithVersion"]),
  41. appNameWithVersion() {
  42. //通过属性访问getters,Getter 会暴露为 store.getters 对象,可以以属性的形式访问这些值:
  43. return this.$store.getters.appNameWithVersion;
  44. },
  45. ...mapGetters(["firstLetter"]),
  46. inputValueLastLetter() {
  47. return this.inputValue.substr(-1, 1);
  48. }
  49. },
  50. methods: {
  51. handlerInput(val) {
  52. this.inputValue = val;
  53. },
  54. //
  55. ...mapMutations([
  56. "SET_USER_NAME", //将 `this.SET_USER_NAME()` 映射为 `this.$store.commit('SET_USER_NAME')`
  57. "SET_APP_NAME" //将 `this.SET_APP_NAME()` 映射为 `this.$store.commit('SET_APP_NAME')`
  58. ]),
  59. ...mapActions([
  60. "updateAppName" //将 `this.updateAppName()` 映射为 `this.$store.dispatch('updateAppName')`
  61. ]),
  62. handleChangeAppName() {
  63. this.SET_APP_NAME({
  64. appName: "newAppName"
  65. });
  66. this.SET_USER_NAME({
  67. userName: "shuyujie"
  68. });
  69. this.$store.commit("SET_APP_VERSION");
  70. },
  71. handleActionChangeAppName() {
  72. //第一种调用Action的方法
  73. //this.$store.dispatch('updateAppName')
  74. //第二种调用Action的方法
  75. this.updateAppName();
  76. },
  77. registerModule() {
  78. this.$store.registerModule(["user", "todo"], {
  79. state: {
  80. todoList: ["学习mutations", "学习actions"]
  81. }
  82. });
  83. }
  84. }
  85. };
  86. </script>

点击名称为:“修改appName和user.js中的userName”的按钮:

效果图:

2.严格模式

在严格模式下,无论何时发生了状态变更且不是由 mutation 函数引起的,将会抛出错误。这能保证所有的状态变更都能被调试工具跟踪到。

index.js代码:

  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. import state from "./state"
  4. import getters from './getters'
  5. import mutations from "./mutations"
  6. import actions from "./actions"
  7. import user from './module/user'
  8. import saveInLocal from './plugin/saveInLocal';
  9.  
  10. Vue.use(Vuex)
  11.  
  12. export default new Vuex.Store({
  13. strict: process.env.NODE_ENV === 'development',//不要在发布环境下启用严格模式!
  14. state,
  15. getters,
  16. mutations,
  17. actions,
  18. modules: {
  19. user
  20. },
  21. plugins:[saveInLocal]
  22. })

3.Vuex+双向数据绑定

当在严格模式中使用 Vuex 时,在属于 Vuex 的 state 上使用 v-model 会比较棘手,因为state只允许被mutation修改。

解决办法:使用带有 setter 的双向绑定计算属性

state.js:

  1. const state = {
  2. appName: 'admin',
  3. stateValue: 'I am stateValue'
  4. }
  5. export default state

mutations.js:

  1. import vue from 'vue'
  2. const mutations = {
  3. SET_APP_NAME(state, params) {
  4. //若params是对象格式
  5. state.appName = params.appName;
  6. //若params是字符串格式
  7. //state.appName = params;
  8. },
  9. SET_APP_VERSION(state) {
  10. vue.set(state, 'appVersion', 'v100.0')
  11. //state.appVersion = 'v2.0'
  12. },
  13. SET_STATE_VALUE (state, value) {
  14. state.stateValue = value
  15. }
  16. }
  17. export default mutations;

store.vue:

  1. <template>
  2. <div>
  3. <a-input v-model="stateValue"/>
  4. <p>{{ stateValue }}</p>
  5. <p>appName: {{ appName }}, appNameWithVersion : {{ appNameWithVersion }}</p>
  6. <p>userName : {{ userName }}, firstLetter is : {{ firstLetter }}</p>
  7. <button @click="handleChangeAppName">修改appName和user.js中的userName</button>
  8. <p>动态给state增加appVersion: {{ appVersion }}</p>
  9. <button @click="handleActionChangeAppName">通过Action修改appName</button>
  10. <button @click="registerModule">动态注册模块</button>
  11. <p v-for="(li, index) in todoList" :key="index">{{ li }}</p>
  12. </div>
  13. </template>
  14. <script>
  15. import AInput from "_c/AInput.vue";
  16. import AShow from "_c/AShow.vue";
  17. //变量的解构赋值
  18. import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
  19. import { stat } from "fs";
  20. export default {
  21. name: "store",
  22. data() {
  23. return {
  24. inputValue: ""
  25. };
  26. },
  27. components: {
  28. AInput: AInput,
  29. AShow: AShow
  30. },
  31. computed: {
  32. //ES6展开操作符 mapState展开会形成一个对象 使用对象展开运算符将此对象混入到外部对象中
  33. ...mapState({
  34. appName: state => state.appName,
  35. appVersion: state => state.appVersion,
  36. userName: state => state.user.userName,
  37. todoList: state => (state.user.todo ? state.user.todo.todoList : [])
  38. }),
  39. // 使用对象展开运算符将 getter 混入 computed 对象中
  40. // ...mapGetters(["appNameWithVersion"]),
  41. appNameWithVersion() {
  42. //通过属性访问getters,Getter 会暴露为 store.getters 对象,可以以属性的形式访问这些值:
  43. return this.$store.getters.appNameWithVersion;
  44. },
  45. stateValue: {
  46. get () {
  47. return this.$store.state.stateValue
  48. },
  49. set (val) {
  50. this.SET_STATE_VALUE(val)
  51. }
  52. },
  53. ...mapGetters(["firstLetter"]),
  54. inputValueLastLetter() {
  55. return this.inputValue.substr(-1, 1);
  56. }
  57. },
  58. methods: {
  59. handlerInput(val) {
  60. this.inputValue = val;
  61. },
  62. //
  63. ...mapMutations([
  64. "SET_USER_NAME", //将 `this.SET_USER_NAME()` 映射为 `this.$store.commit('SET_USER_NAME')`
  65. "SET_APP_NAME", //将 `this.SET_APP_NAME()` 映射为 `this.$store.commit('SET_APP_NAME')`
  66. 'SET_STATE_VALUE'
  67. ]),
  68. ...mapActions([
  69. "updateAppName" //将 `this.updateAppName()` 映射为 `this.$store.dispatch('updateAppName')`
  70. ]),
  71. handleChangeAppName() {
  72. this.SET_APP_NAME({
  73. appName: "newAppName"
  74. });
  75. this.SET_USER_NAME({
  76. userName: "shuyujie"
  77. });
  78. this.$store.commit("SET_APP_VERSION");
  79. },
  80. handleActionChangeAppName() {
  81. //第一种调用Action的方法
  82. //this.$store.dispatch('updateAppName')
  83. //第二种调用Action的方法
  84. this.updateAppName();
  85. },
  86. registerModule() {
  87. this.$store.registerModule(["user", "todo"], {
  88. state: {
  89. todoList: ["学习mutations", "学习actions"]
  90. }
  91. });
  92. }
  93. }
  94. };
  95. </script>

AInput.js:

  1. <template>
  2. <div>
  3. <input @input="handleInput" :value="value"/>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. name:'AInput',
  9. props:{
  10. value:{
  11. type:[String,Number],
  12. default:''
  13. }
  14. },
  15. methods:{
  16. handleInput(event){
  17. const value=event.target.value;
  18. this.$emit('input',value);
  19. }
  20. }
  21. }
  22. </script>

效果图:

Vuex进阶的更多相关文章

  1. 「后端小伙伴来学前端了」Vuex进阶操作,让你的代码更加高效(简称如何学会偷懒 【手动狗头】)

    学妹手机里的美照 前言 前一篇写了Vuex基本使用,用起来还稍稍有些繁琐,代码有很多 冗余的地方,这篇就带着大家用更简单的方式来使用Vuex(其实就是怎么更好的偷懒,用更少的代码来完之前的事情) 进入 ...

  2. Redux进阶(像VUEX一样使用Redux)

    更好的阅度体验 前言 redux的问题 方案目标 如何实现 思考 前言 Redux是一个非常实用的状态管理库,对于大多数使用React库的开发者来说,Redux都是会接触到的.在使用Redux享受其带 ...

  3. vue从入门到进阶:Vuex状态管理(十)

    Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化. 在 Vue 之后引入 vuex 会进行自动 ...

  4. 【前端vue进阶实战】:从零打造一个流程图、拓扑图项目【Nuxt.js + Element + Vuex】 (一)

    本系列教程是用Vue.js + Nuxt.js + Element + Vuex + 开源js绘图库,打造一个属于自己的在线绘图软件,最终效果:topology.le5le.com .如果你觉得好,欢 ...

  5. vue进阶:vuex(数据池)

    非父子组件传值 vuex 一.非父子组件传值 基于父子组件通信与传值实现非父子组件传值的示例关键代码: <template> <div> <!-- 学员展示 --> ...

  6. Vuex入门、同步异步存取值进阶版

    关注公众号查看原文: 1. vueX介&绍安装 Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方 ...

  7. vuex 初体验

    vuex是vue的状态管理工具,vue进阶从es6和npm开始,es6推荐阮一峰大神的教程. vuex学习从官方文档和一个记忆小游戏开始.本着兴趣为先的原则,我先去试玩了一把-->. Vuex ...

  8. [vue最新实战] gank客户端(vue2 + vue-router2 + vuex +webpace + es6)新手福利,干货多多

    vue-meizi 本项目是基于vue2最新实战项目,是适合新手进阶的绝佳教程.代码简单易懂,注释多多.实现了移动端使用最多的 无限滚动,图片加载,左右滑动,等待.先发布预览版本,后面更多更全的功能和 ...

  9. 简单的vuex 的使用

    1. npm install vuex 2. 在src 下 新建文件夹 store (为什么是这个单词,vuex 是用来状态管理的,用储存一些组件的状态,取存贮之意),store 文件下 新建文件 i ...

随机推荐

  1. elasticsearch 插件 大全

    本文使用的elasticsearch版本:1.7.3 推荐几款比较常用的elasticsearch插件 1.集群监控插件 bigdesk node cluster 2.集群资源查看和查询插件 kopf ...

  2. 信息检索和自然语言处理 IR&NLP howto

    课程: 6.891 (Fall 2003): Machine Learning Approaches for Natural Language Processing http://www.ai.mit ...

  3. Murano Weekly Meeting 2015.08.11

    Meeting time: 2015.August.11th 1:00~2:00 Chairperson:  Serg Melikyan, PTL from Mirantis Meeting summ ...

  4. swing线程机制

    在介绍swing线程机制之前,先介绍一些背景概念. 背景概念 同步与异步:     同步是指程序在发起请求后开始处理事件并等待处理的结果或等待请求执行完毕,在此之前程序被阻塞(block)直到请求完成 ...

  5. empty,isset,is_null比较(差异与异同)

    做php开发时候,想必在使用:empty,isset,is_null  这几个函数时候,遇到一些问题.甚至给自己的程序带来一些安全隐患的bug.很多时候,对于isset,empty都认为差不多.因此开 ...

  6. java虚拟机之GC(转)

    垃圾回收主要内容: 1. 那些内存需要回收? 2. 什么时候回收? 3. 如何回收? 垃圾回收主要针对运行时数据区那些区域? 运行时数据区的线程私有区域有:虚拟机栈,本地方法栈,程序计数器等: 栈中的 ...

  7. sass随笔

    一.前期准备       sass基于ruby     (1)   安装ruby  从http://rubyinstaller.org/downloads/下载 双击下载的程序进行安装,勾选如下图的选 ...

  8. (九)JavaScript之【JS函数(定义、参数、调用、【闭包】、call(),apply())】[较深,胆小勿进]

    一].定义: /** * 函数表达式 * * Function() 构造函数 * * 函数提升(Hoisting) * JavaScript默认将当前作用域提升到前面去 * Hoisting应用在变量 ...

  9. C++ Knowledge series Template & Class

    Function Function is composed of name, parameter (operand, type of operand), return value, body with ...

  10. Azure 5 月新公布(二)

    Azure 5 月新发布(二):CDN 图片处理功能, CDN Restful API, 新版 CDN 管理门户, 计量名称变更延期  Azure CDN 图片处理功能开放公共预览版 Azure CD ...