zoukankan      html  css  js  c++  java
  • 使用vuex的流程随笔

    1.在建好的vue项目中新建一个vuex文件夹在此文件夹下建一个index.js文件,在此文件下引入vuex 模块(当然需要先npm下载)和vue模块,在引入你所有的自定义的module.js模块(下边会讲module的内容),然后使用vuex

    Vue.use(Vuex) ;在导出时新创建一个Vuex的Store的对象,在这个对象中使用modules:{把你自定义的模块赋值}代码如下:

                                 import Vuex from 'vuex'
                                 import Vue from 'vue'

                                 import home from '../page/home/moudlehome.js';
                                 import city from '../page/city/moudlecity.js';
                                 Vue.use(Vuex);

                                 export default new Vuex.Store({

                             
                                  modules:{
                                     home:home,  //this.$store.state.home
                                     city:city           //this.$store.state.city
                                              }
                                  })

    2.在module.js中使用vuex的核心内容并发送axios请求(前提是在页面渲染完后就发送请求所以需要在总组件中设置mounted() { if(this.$store.getters.shouldGetData){
                this.$store.dispatch("getSwiperInfo");
            }  }来传值给module中的actions并且在getSwiperInfo()函数中发送axios异步请求,代码如下:

    import axios from 'axios';
    export default {

    //数据内容
         state:{
                swiperInfo: [],
                swiperInfo1: []
         },
        //异步操作
         actions:{
             getSwiperInfo(context){
                 axios.get('/static/index.json')
                    .then((response)=>{
                        if (response.status === 200) {
                          const {data}  = response.data;
                          context.commit("changeSwiperInfo",data)
                        }
                    })    
             }
         },

     //对数据内容的更新
         mutations:{
             changeSwiperInfo:(state,data)=>{
                 state.swiperInfo = data.swiperInfo;
                 state.swiperInfo1 = data.swiperInfo1
             }
         },

    //对数据的二次包装对网页的一种优化
         getters:{
             shouldGetData(state){
                 if(!state.swiperInfo.length&&
                    !state.swiperInfo1.length){
                        return true;
                    }else{
                        return false;
                    }             
             }
         }
    }

    3.在子组件中绑定并使用数据、

          在子组件中使用

         computed:{
                   swiperInfo(){
                   return     this.$store.state.home.swiperInfo;
                   }
            }

    绑定数据

    然后就可以在你的实例化循环中使用swiperInfo in item来使用数据了

  • 相关阅读:
    Java中Vector和ArrayList的区别
    多线程
    集合框架
    5种运行时异常+1道面试题
    事务,视图,索引,备份和恢复
    MYSQL常用函数
    SQL数据库表字段明细导入导出
    SqlServer 命令方式备份与还原
    .NetCore IIS发布后PUT、DELETE请求错误405.0
    大数据中HBase的Java接口封装
  • 原文地址:https://www.cnblogs.com/cnlg123/p/7808021.html
Copyright © 2011-2022 走看看