vueRouter动态路由匹配

感情迁移 提交于 2020-03-05 11:55:48

vueRouter动态路由匹配

动态路由匹配需要安装vue-router
在控制台选择安装的路径
npm init --yes
npm install vue-router -S

html代码块

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态路由匹配</title>
</head>
<body>
    <div id="app"></div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="./node_modules/vue-router/dist/vue-router.js"></script>
</body>
</html>

js代码块

    <script type="text/javascript">
        var ComDesc = {
            data(){
                return{
                    msg:''
                }
            },
            template:`
                <div>
                    我是{{msg}}
                </div>  
            `,
            created(){
                this.msg = 'frontend';
                
            },
            watch:{
                '$route'(to,from){
                    // console.log(to);
                    // console.log(from);
                    this.msg = to.params.id;
                }
            }
        };
        var TimeLine = {
            template:`
                <div id="timeline">
                    <router-link :to="{name:'ComDesc',params:{id:'frontend'}}">前端</router-link>
                    <router-link :to="{name:'ComDesc',params:{id:'backend'}}">后端</router-link>

                    <router-view></router-view>
                </div>  
            `
        };
        var Pins = {
            template:`
                <div>
                    我是个沸点肥肥的
                </div>
            `
        };
        var router = new VueRouter({
            routes:[
                {
                    path:'/timeline',
                    component:TimeLine,
                    children:[
                        {
                            name:'ComDesc',
                            path:'/timeline/:id',
                            component:ComDesc
                        }
                    ]
                },
                {
                    path:'/pins',
                    component:Pins
                },
            ]
        });
        var App = {
            template:`
                <div>
                    <router-link to='/timeline'>首页</router-link>
                    <router-link to='/pins'>沸点</router-link>

                    <router-view></router-view>
                </div>
            `,
        };
        new Vue({
            el:'#app',
            components:{
                App
            },
            router,
            template:`<App />`
        });
    </script>

另外使用包裹App中的可以对组件进行缓存,减少重复摧毁创建的消耗。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!