感受最不爽的地方,是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