成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

基于requirejs的vue2項(xiàng)目(二)

tianren124 / 2133人閱讀

摘要:減少服務(wù)器的請(qǐng)求對(duì)于和這兩個(gè)特殊寫(xiě)發(fā)的文件因?yàn)榈拇虬蛔R(shí)別,要進(jìn)行特殊處理

上一節(jié)提完了構(gòu)思和大體實(shí)現(xiàn)下面來(lái)看具體的

配置文件config

配置文件主要是是用來(lái)讓后端開(kāi)發(fā)自主添加頁(yè)面,并通過(guò)該配置生成route和加載對(duì)應(yīng)的store,這樣就省去了后端去了解vue-router和vuex的用法了;

配置文件格式如下

這里采用umd格式開(kāi)頭是為了后續(xù)nodejs進(jìn)行調(diào)用

(function(global, factory) {
    typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() :
        (global.__config__ = factory());
})(this, function() {
    var __config__ = {
        //規(guī)則說(shuō)明
        /**
         * route : 路由
         * path  : 模塊路徑
         * store : 是否加載對(duì)應(yīng)store
         * sync  : 是否同步加載
         */
        modules: [
            { route: "/", path: "Login", store: true, sync:true },
            { route: "/Main", path: "Main" },
            ...
        ]
    }
});
路由router

有了上面的config文件,我們就可以通過(guò)配置來(lái)來(lái)生成router了

代碼如下

在define前根據(jù)config動(dòng)態(tài)define一些模塊用來(lái)給業(yè)務(wù)模塊動(dòng)態(tài)返回template和mixin一些公用方法

;
(function () {
  var businessModules = ["vue", "store/index", "vue-router"].concat(__config__.map(function (o) {
    var module = o
      .route
      .replace(//:[^/]*/g, "")
      .replace(///g, "_")
    if (o.sync) {
      var func = ";define("business/base/" + module + "",["__module__","business/" + o.path + "/index","text!business/" + o.path + "/tpl.html"],function(factory,businessModule,template){ return factory("" + module + "", businessModule("" + module + ""),template)})"
      __config__.dynamic(func)
      return "business/base/" + module
    }
  }))
  define(businessModules, function (Vue, store, VueRouter) {
    Vue.use(VueRouter)
    var m = []
      .slice
      .call(arguments, 3)
    var routes = __config__.map(function (o, i) {
      var clone = Object.assign({}, o)
      clone.name = clone
        .route
        .replace(//:[^/]*/g, "")
        .replace(///g, "_")
      delete clone.store
      clone.path = clone.route
      delete clone.route
      clone.component = clone.sync
        ? m[i]
        : function (resolve) {
          require(["__module__", "business/" + o.path + "/index", "text!business/" + o.path + "/tpl.html"], function (factory, businessModule, template) {
            resolve(factory(clone.name, businessModule(clone.name), template))
          })
        }
      return clone
    })
    var router = new VueRouter({mode: "hash", routes: routes})
    var firstLoad = true
    var goto = function (to, from, next) {
      var tName = to.name || "_"
      var fName = from.name || "_"
      var toDepth = tName
        .split("_")
        .length
      var fromDepth = fName
        .split("_")
        .length
      toDepth += (tName === "_"
        ? -1
        : 0)
      fromDepth += (fName === "_"
        ? -1
        : 0)
      var direction = toDepth - fromDepth
      if (firstLoad && toDepth > 0) {
        firstLoad = false
        next({path: "/"})
      } else {
        store.dispatch("transition", {
          direction: direction,
          to: tName,
          from: fName
        })
        window.setTimeout(function () {
          next()
        })
        firstLoad = false
      }
    }
    router.beforeEach(function (to, from, next) {
      var args = arguments
      if (to.path === "/") {
        goto.apply(this, args)
        return
      }
      store
        .dispatch("auth")
        .then(function () {
          goto.apply(this, args)
        }, function () {
          Vue.$toast({message: "驗(yàn)證信息已失效,請(qǐng)重新登陸", iconClass: "fa fa-close"})
          window.setTimeout(function () {
            next({path: "/"})
          })
        })
    })

    return {tpl: "", router: router}
  })
})()

狀態(tài)管理store

在define前根據(jù)config動(dòng)態(tài)define一些模塊用來(lái)給store對(duì)象添加一些公用getter,mutations和action

(function() {
    var storeModules = [
        "vue",
        "vuex",
        "./transition"
    ].concat(__config__.modules.map(function(o) {
        var module = o.route.replace(///g, "_");
        var func = (o.store == true ?
            ";define("store/modules/base/" + module + "",["__store__factory__","store/modules/" + o.path + "/store"],function(factory,storeModule){ var mb = factory("" + module + ""); var m = new storeModule("" + module + ""); var c = $.extend(true,{},mb, m);  return c; });" :
            ";define("store/modules/base/" + module + "",["__store__factory__"],function(factory){ return factory("" + module + "");});");
        __config__.dynamic(func);
        return "store/modules/base/" + module;
    }));

    define(storeModules, function(Vue, Vuex, transition) {
        Vue.use(Vuex);
        var m = [].slice.call(arguments, 3);
        var modules = {};
        __config__.each(function(o, i) {
            modules[o.route.replace(///g, "_")] = m[i];
        });
        return new Vuex.Store({
            state: {},
            mutations: {},
            actions: {
                transition: transition
            },
            modules: modules
        })
    })
})();
vue主程序定義
define([
    "vue",
    "vue-router",
    "store/index",
    "router/index",
    "emitter",
    "__install__" //這里面主要是對(duì)公用控件的一些初始化 Vue.component({...})
], function(Vue, VueRouter, store, router, Emitter) {
    window.Vue = Vue;
    return {
        run: function() {
            Vue.config.silent = false;
            Vue.config.devtools = true;
            Vue.mixin(Emitter);
            var $vm = new Vue({
                el: "body > div",
                store: store,
                template: router.tpl,
                router: router.router
            });
        }
    }
})
模塊業(yè)務(wù)的寫(xiě)法

以Login模塊為例

文件路徑/business/Login/index.js
同目錄下還有個(gè)tpl.html

define(["vue", "vuex"], function(Vue, Vuex) {
    return function module(moduleName) {
        return {
            data: function() {
                return {
                    username: "",
                    password: ""
                }
            },
            methods: Object.assign(
                Vuex.mapActions([
                    "verify"
                ]), {
                    sign: function() {
                        var that = this;
                        this.verify({ username: this.username, password: this.password }).then(function() {
                            that.$router.push("/Main");
                        }, function(mes) {
                            Vue.$toast({
                                message: mes || "帳號(hào)或者密碼錯(cuò)誤",
                                iconClass: "fa fa-close"
                            });
                        });
                    }
                })
        }
    }
})

對(duì)應(yīng)的store

文件為/store/module/Login/store.js

define(function() {
    return function storeModule(module) {
        this.state = {
            sign: true,
            auth: "" //用于存儲(chǔ)登陸成功后的驗(yàn)證碼,用于后繼登陸狀態(tài)驗(yàn)證
        }
        this.getters = {
            isLogin: function(state) {
                return state.sign;
            }
        }
        this.mutations = {
            success: function(state, param) {
                state.sign = true;
                state.auth = param ? param : state.auth;
            },
            fail: function(state) {
                state.sign = false;
                state.auth = "";
            }
        }
        this.actions = {
            //頁(yè)面跳轉(zhuǎn)過(guò)程中驗(yàn)證用
            verify: function(content, opt) {
                return new Promise(function(resolve, reject) {
                    $.post("/api/verify", { username: opt.username, password: opt.password }).then(function(data) {
                        if (data.state) {
                            content.commit("success", data.auth);
                            resolve();
                        } else {
                            content.commit("fail");
                            reject();
                        }
                    }, function() {
                        content.commit("fail");
                        reject("服務(wù)器錯(cuò)誤!請(qǐng)聯(lián)系管理員");
                    });
                })
            },
            //登陸用
            auth: function(content) {
                return new Promise(function(resolve, reject) {
                    $.get("/api/auth", { auth: content.state.auth }).then(function(data) {
                        if (data) {
                            content.commit("success");
                            resolve(data);
                        } else {
                            content.commit("fail");
                            reject();
                        }
                    });
                });
            }
        }
    }
})

平時(shí)后端開(kāi)發(fā)時(shí)不涉及全局狀態(tài)控制時(shí)就可以不用store,ajax可以直接寫(xiě)在模塊內(nèi)

以上就是基于requirejs的vue2項(xiàng)目的核心內(nèi)容

該項(xiàng)目在不打包的情況下能夠正常運(yùn)行,各模塊都會(huì)在頁(yè)面加載時(shí)進(jìn)行預(yù)加載;后繼還將進(jìn)行所有文件打。減少服務(wù)器的請(qǐng)求對(duì)于store和router這兩個(gè)特殊寫(xiě)發(fā)的文件(因?yàn)閞equirejs的r.js打包不識(shí)別),要進(jìn)行特殊處理

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/86793.html

相關(guān)文章

  • 基于requirejsvue2項(xiàng)目 (一)

    摘要:項(xiàng)目截圖項(xiàng)目演示地址該項(xiàng)目主要是解決如何讓不了解前端構(gòu)建,并負(fù)責(zé)大部分業(yè)務(wù)邏輯的后端開(kāi)發(fā)出一個(gè)單頁(yè)應(yīng)用覺(jué)得有用請(qǐng)給個(gè)推薦,謝謝最近做了一次小更新配置文件可以配置模塊是否異步加載以及是否關(guān)聯(lián)開(kāi)發(fā)背景公司推進(jìn)手機(jī)端項(xiàng)目,但目前開(kāi)發(fā)模式依舊是后端 項(xiàng)目截圖 項(xiàng)目演示地址 該項(xiàng)目主要是解決: 如何讓不了解前端構(gòu)建,并負(fù)責(zé)大部分業(yè)務(wù)邏輯的后端 開(kāi)發(fā)出 一個(gè)單頁(yè)應(yīng)用 覺(jué)得有用請(qǐng)給個(gè)推薦,謝謝 最近...

    jackzou 評(píng)論0 收藏0
  • 基于requirejsvue2項(xiàng)目 (三)

    摘要:這里是打包篇使用的是的進(jìn)行打包思路是通過(guò)里面的進(jìn)行項(xiàng)目的初打包因?yàn)楹屠锩娴囊檬莿?dòng)態(tài)生成的所以無(wú)法對(duì)其進(jìn)行處理這里我們用到了來(lái)進(jìn)行文件整合具體看代碼這里是通過(guò)配置文件來(lái)組裝配置信息對(duì)設(shè)置了同步的模板進(jìn)行打包這里是通過(guò) 這里是打包篇 使用的是requirejs的r.js進(jìn)行打包 思路是,通過(guò)entrance.js里面的require.config進(jìn)行項(xiàng)目的初打包 因?yàn)閞outer.js和...

    lijy91 評(píng)論0 收藏0
  • 前端資源系列(4)-前端學(xué)習(xí)資源分享&前端面試資源匯總

    摘要:特意對(duì)前端學(xué)習(xí)資源做一個(gè)匯總,方便自己學(xué)習(xí)查閱參考,和好友們共同進(jìn)步。 特意對(duì)前端學(xué)習(xí)資源做一個(gè)匯總,方便自己學(xué)習(xí)查閱參考,和好友們共同進(jìn)步。 本以為自己收藏的站點(diǎn)多,可以很快搞定,沒(méi)想到一入?yún)R總深似海。還有很多不足&遺漏的地方,歡迎補(bǔ)充。有錯(cuò)誤的地方,還請(qǐng)斧正... 托管: welcome to git,歡迎交流,感謝star 有好友反應(yīng)和斧正,會(huì)及時(shí)更新,平時(shí)業(yè)務(wù)工作時(shí)也會(huì)不定期更...

    princekin 評(píng)論0 收藏0
  • 大前端 - 收藏集 - 掘金

    摘要:是目前唯一一個(gè)支持同步調(diào)用的跨平臺(tái)年度上最多的個(gè)項(xiàng)目前端掘金年接近尾聲,在最近的幾篇文章中,會(huì)整理總結(jié)一些年度開(kāi)源項(xiàng)目。 JS 全棧教程 - 前端 - 掘金本課程是基于阮一峰的 js 全棧教程的視頻版本,免費(fèi)供大家觀看... 2016 年 10 個(gè)最佳的 CodePen 作品 - 前端 - 掘金說(shuō)到 CodePen,前端開(kāi)發(fā)者們肯定不會(huì)陌生。如果說(shuō) Dribbble 是設(shè)計(jì)師們聚集的圣...

    honhon 評(píng)論0 收藏0
  • 前方來(lái)報(bào),八月最新資訊--關(guān)于vue2&3最佳文章推薦

    摘要:哪吒別人的看法都是狗屁,你是誰(shuí)只有你自己說(shuō)了才算,這是爹教我的道理。哪吒去他個(gè)鳥(niǎo)命我命由我,不由天是魔是仙,我自己決定哪吒白白搭上一條人命,你傻不傻敖丙不傻誰(shuí)和你做朋友太乙真人人是否能夠改變命運(yùn),我不曉得。我只曉得,不認(rèn)命是哪吒的命。 showImg(https://segmentfault.com/img/bVbwiGL?w=900&h=378); 出處 查看github最新的Vue...

    izhuhaodev 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<