zoukankan      html  css  js  c++  java
  • vuex vue状态管理

    第一步安装vuex(安装在生产环境)

    npm install vuex

    第二步 src下新建store文件夹 用来专门放状态管理,store文件夹下新建四个js文件 index.js  actions.js  mutations.js getters.js(后面会一一介绍这几个文件的作用)

    第三步 main.js中引入store

    import store from './store'

    main.js中实例化的时候使用store

    new Vue({
       el:'#app',
       store,//挂载stroe
       router,
       template:'<App>'   ,
       components:{App}      
    })

    基础工作做完了,可以开始第一个demo了

    vuex共分四个模块,components即组件,数据展示修改层面,actions业务处理事务转发,mutations具体的业务逻辑处理,getters拿到处理好后的数据返给components

    四个模块可以都写在index.js里也可以单独写,然后在index.js里引入,这里是单独写再引入的

    index.js

    import Vue from 'vue'//引入vue
    import Vuex from 'vuex'//引入vuex
    
    import * as actions from './actions'
    import * as mutations from './mutations'
    import * as getters from './getters' //*即所有
    
    Vue.use(Vuex)
    
        onst state = {
      number:123  
    }
    
    //注册上面各个模块
    const store = new Vuex.Stroe({
       state,getters,actions,mutations 
    })
    
    expoort default store

    state{}数据存放位置,现在里面有个number数据为123

    其实现在已经可以在组件里面用这个数据了,通过this.$store.state.number 只是官方不建议这么用

    从页面开始

    componentsA.vue

    <template>
        <div>
            <p>vuex中的数据{{number}}</p>
           <button @click='modifynumber'>修改number</button>
        </div>
    </template>
    <script>
        import{mapActions,mapGetters} from 'vuex' // 语法糖
         //mapActions 相当于this.$store.dispatch('请求类型',数据) 发送请求
        //mapGetters 相当于this.$store.getters.number
    
        export default{
            data(){
              retrun{
                    
                }  
            },
            methods:{
               ...mapActions(
                      ['modifynumber']//提交方法  
                    ), 
                
            },
            computed:{
              ...mapGetters(['number'])  //获取state中的数据
            }
        }    
    </script>

    mapActions写在methods中  mapGetters写在computed中

    mutations中做具体的业务逻辑处理

    mutations.js

    export const modifynumber = (state) =>{
      state.number ++  
    }

    getters.js

    export const number = (state) =>{ return state.number}

     大概就是这些了

    I love three things in the world: the sun, the moon, and you. The sun for day, the moon for night, and you forever. 

    浮世万千,吾爱有三,日 月  与卿,日为朝,月为暮,卿为朝朝暮暮。

  • 相关阅读:
    强化学习 | D3QN原理及代码实现
    Airtest入门及多设备管理总结
    JS图片base64压缩
    ABP框架
    .net gof23种设计模式
    VS2013添加Socket
    VS2013用InstallShield打包winfrom项目
    .net core3.1 log4net无法写日志
    git commit 修改提交说明信息
    screen 使用总结
  • 原文地址:https://www.cnblogs.com/wong-do/p/9500327.html
Copyright © 2011-2022 走看看