[英]Loading Default Component - Vue.js CDN
默認情況下,該頁面在頁面上如何加載<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>
對於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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.