Razor Pages如何结合Vue实现动态组件单页应用

这篇文章主要介绍Razor Pages如何结合Vue实现动态组件单页应用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

基本页面结构

Index页面做为主页面, 其它页面只是下载模板和相关的vue组件代码。 暂时加载组件使用了个全局函数,改成vue的方法也不难。

Index中引入jquery、vue、vue-router、element-ui相关的CSS和JS文件。

在Index中实现路由相关功能

    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   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'); 它会判断组件是否加载过, 进而决定是不是需要异步加载组件。

以上是“Razor Pages如何结合Vue实现动态组件单页应用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!