感受最不爽的地方,是vue-router的懶加載不夠動態,須要事先把路徑註冊好。 也許vue-router的動態路由能實現的更好些,目前沒有時間多作研究,先寫個總結。html
Index頁面作爲主頁面, 其它頁面只是下載模板和相關的vue組件代碼。 暫時加載組件使用了個全局函數,改爲vue的方法也不難。vue
const pages = {}; const routes = [ { path: '/login', component: () => Promise.resolve(pages['login']) } , { path: '/home', component: () => Promise.resolve(pages['home']) }, ] const router = new VueRouter({ routes: routes // (縮寫) 至關於 routes: routes }) const vueMain = new Vue({ el: "#app", router:router }) vueMain.$router.push('login'); function load(routePath) { console.log(routePath) if (typeof (pages[routePath]) != "undefined") { console.log("Route to: " + routePath); vueMain.$router.push(routePath); return; } const url = '@Url.Content("~/")' + routePath; console.log("url: " + url); $.get(url, {}, rsp => { $("#components").append(rsp); vueMain.$router.push(routePath); }) }
<template id="tplLogin"> <el-form style="max-width:600px; margin:20px auto;" method="post"> @Html.AntiForgeryToken() <el-form-item label="用戶名:"> <el-input v-model="loginData.userName" maxlength="30" minlength="2" @@input="inputUserName" placeholder="請輸入用戶名."> </el-input> </el-form-item> <el-form-item class="text-center"> <el-button type="primary" icon="el-icon-check" @@click="doLogin" :disabled="!canLogin">肯定</el-button> </el-form-item> </el-form> </template> <script> pages["login"] = Vue.component('login', { template: "#tplLogin", data: function () { return { loginData: { userName: '' }, canLogin:false }; }, methods: { doLogin: function () { $.post('Login', this.loginData, function (rsp) { console.log("Login Result: " + rsp); load('home'); }); }, inputUserName: function () { this.canLogin = this.loginData.userName.trim().length > 2; } } }) </script>
能夠看到關鍵的方法是 load('home'); 它會判斷組件是否加載過, 進而決定是否是須要異步加載組件。jquery