VueRouter-命名视图

  背景:

        在一个url中(一个页面中)使用多个组件,此时,需要为组件进行命名,然后通过命名区分各组件的使用位置

        用法:

        1、在写路由时,将原先的`component`多加一个`s`改为`components`,并且以键值对的形式进行命名。
        let router = new VueRouter({
            routes: [{
                path: "/",
                components: {
                    default: index,
                    a: content,
                    b: aboutUs,
                }
            }]
        })
        2、在调用时,在`<router-view>`增加`name`属性,进行指明使用的是哪个组件。如果不写,则name默认为`default`
    <div id="app">
        <router-view></router-view>
        <router-view name="a"></router-view>
        <router-view name="b"></router-view>
    </div>

  整体代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
    <title>VueRouter-命名视图</title>
</head>

<body>
    <div id="app">
        <router-view></router-view>
        <router-view name="a"></router-view>
        <router-view name="b"></router-view>
    </div>
    <script>
        let index = Vue.extend({
            template: "<h1>首页</h1>"
        })
        let aboutUs = Vue.extend({
            template: "<h1>关于我们</h1>"
        })
        let content = Vue.extend({
            template: "<h1>正文</h1>"
        })
        let router = new VueRouter({
            routes: [{
                path: "/",
                components: {
                    default: index,
                    a: content,
                    b: aboutUs,
                }
            }]
        })
        new Vue({
            el: "#app",
            router,
        })
    </script>
</body>

</html>

 

posted @ 2020-02-25 19:59  xsan  阅读(277)  评论(0编辑  收藏  举报