基本例子
<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="/user/foo">f</router-link>
<router-link to="/user/bar">b</router-link>
</p>
<router-view></router-view>
</div>
<script>
const User = {
template: `<div> {{ $route.params.xx }}</div>`
}
const router = new VueRouter({
routes: [
{ path: '/user/:xx', component: User }
]
})
const app = new Vue({ router }).$mount('#app')
</script>
這種也可以
<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="/foo">f</router-link>
<router-link to="/bar">b</router-link>
</p>
<router-view></router-view>
</div>
<script>
const User = {
template: `<div> {{ $route.params.xx }}</div>`
}
const router = new VueRouter({
routes: [
{ path: '/:xx', component: User }
]
})
const app = new Vue({ router }).$mount('#app')
</script>
等價于
<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="/foo">f</router-link>
<router-link to="/bar">b</router-link>
</p>
<router-view></router-view>
</div>
<script>
const User = {
template: `<div> {{ $route.params.xx }}</div>`
}
const routes=[
{ path: '/:xx', component: User }
]
const router = new VueRouter({
routes
})
const app = new Vue({ router }).$mount('#app')
</script>
再由
<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="/foo">f</router-link>
<router-link to="/bar">b</router-link>
</p>
<router-view></router-view>
</div>
<script>
const User = {
template: `<div> doubi</div>`
}
const routes=[
{ path: '/:xx', component: User }
]
const router = new VueRouter({
routes
})
const app = new Vue({ router }).$mount('#app')
</script>
總結(jié)
路由的關(guān)鍵是理解如何綁定地址和組件