【问题标题】:Loading Default Component - Vue.js CDN加载默认组件 - Vue.js CDN
【发布时间】:2019-06-05 20:38:21
【问题描述】:

我如何加载一个组件在<router-view>当页面默认在那个页面的时候?我想在没有:id时有一个默认值

 <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>


    <div id="app">
        <p>
            <router-link to="/product">/product</router-link>
            <router-link to="/product/foo">/product/foo</router-link>

        </p>
        <router-view>

        </router-view>
    </div>
    <script>
    const Product = {template: `<div class="user"> <h2>User {{ $route.params.id }}</h2></div> `}

    const router = new VueRouter({

    routes: [
        {
            path: '/product/:id', component: Product, 
        }
    ],

    mode: 'history',

    })

    const app = new Vue({ 
        router 
    })

    .$mount('#app')

    </script>

【问题讨论】:

标签: javascript vue.js


【解决方案1】:

vue 路由器可以使用可选参数。

所以你可以写path: '/product/:id?而不是path: '/product/:id'(在末尾添加?

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
    <p>
        <router-link to="/product">/product</router-link>
        <router-link to="/product/foo">/product/foo</router-link>
    </p>

    <router-view></router-view>
</div>

<script>
    const Product = {
        /*
            router `id` will be passed as prop
            so we can use `id` in our templates instead of $route.params.id
            this way we can also specify the default value is nothing was passed
         */
        template: `<div class="user"> <h2>User {{ id }}</h2></div> `,
        props: {
            id: {
                type:    String,
                // specify default value if id is not passed to the router
                default: 'N/A'
            }
        }
    }

    const router = new VueRouter({
        mode: 'history',
        routes: [
            {
                // :id? means that it's an optional parameter
                path: '/product/:id?',
                component: Product,
                // Passing Props to Route Components
                props:     true
            },
        ],
    })

    const app = new Vue({
        router
    })
    .$mount('#app')

</script>

【讨论】:

  • 您知道我如何将const Product 中的模板制作为外部文件吗?
  • This answer 应该有帮助
猜你喜欢
  • 2019-01-03
  • 2023-03-05
  • 2018-05-08
  • 2017-11-17
  • 2020-10-30
  • 2020-07-31
  • 2022-11-03
  • 2018-10-31
  • 2019-07-31
相关资源
最近更新 更多