zoukankan      html  css  js  c++  java
  • vueX

    1. Vuex:是一个集中式状态管理工具,相当于react中的 redux

          1) 主要解决的问题:大中型项目中复杂组件通讯问题
      
      
        2)  vuex操作流程:
      
                   dispatch                   commit
      

      vue组件---------------->actions------------>mutations------->state-------->vue组件更新

         3)vuex的重要概念:
    
              state:要保存的状态
              mutations:是最终改变状态的方法集,mutations中的代码是同步执行的
              actions:
    
    
        4)使用步骤:
    
            第一步:先安装vuex
    
                  npm install vuex --save
    
           第二步:在src创建一个store目录,用来存放vuex相关文件
    
            第三步:在store目录先创建一个index.js文件,做为vuex入口文件
    
          第四步:在store目录的index.js中,写入下面的内容
    
                    //引入vuex,vue
                    import Vuex from 'vuex';
                    import Vue from 'vue';
                    
                    //让vue识别vuex
                    Vue.use(Vuex);
                    
                    
                    //存储状态
                    const state={
                         userinfo:{
                             username:'张三',
                             age:20,
                             token:'1001'
                         }
                    }
                    
                //将vuex暴露出去
                export default new Vuex.Store({
                
                    state
                
                });
    
       第五步:在main.js中引入store,并在new Vue中注册
    
                  //引入vuex
                import store from './store';
                new Vue({
                .......
                  store,
                  ........
                });
    
    
     第六步:如何获取和设置数据
    
       获取:在对应组件的computed中处理
    
          即: this.$store.state来获取
    
     设置/修改数据:通过commit到mutations来修改state
    
    如何提高vuex的使用体验:
    
       1.优化state写法
       import {matpState}  from 'vuex'
    

    在计算属性中添加下面的内容:

           computed:{
              //组件的计算属性
                str() {
                    return "hello"+this.msg
        
                },
           //vuex的数据
                ...mapState({
                address:'address',
                userinfo:'userinfo'
        
                })
        
            }
        }
    

    2.优化actions,mutations

            import { mapState,mapActions,mapMutations  } from 'vuex';
           ...mapActions(['gomodify','aa','bb']),
           ...mapMutations(['setValue']),
    
     3.隔离vuex各部分,提高可维护性
  • 相关阅读:
    ssh登录 The authenticity of host 192.168.0.xxx can't be established. 的问题
    Linux学习安装
    linux中的虚拟环境工具
    linux 文件目录权限
    PHP利用百度ai实现文本和图片审核
    Laravel + Swoole 打造IM简易聊天室
    Mysql索引降维 优化查询 提高效率
    Nginx支持比Apache高并发的原因
    网站高并发解决方案(理论知识)
    mysql大量数据分页查询优化-延迟关联
  • 原文地址:https://www.cnblogs.com/zbcry/p/9052927.html
Copyright © 2011-2022 走看看