import Vue from 'vue';
import VueRouter from 'vue-router';
// inject Vue Router to Vue
Vue.use(VueRouter);
// components
const Foo = { template: '<div>Foo</div>' };
const Bar = { template: '<div>Bar</div>' };
const Asd = { template: '<div>Asd</div>' };
// Vue Router configuration
const routes = [
{
name: 'user',
path: '/user',
// 注意,此处是 components,不是 component,末尾的 's' 需要注意
components: {
default: Foo, // <router-view> 没有使用 name 指定组件时就显示 default 指定的组件
a: Bar,
b: Asd,
},
},
];
// Vue Router instance
const router = new VueRouter({
routes,
});
// Vue instance
const app = new Vue({
router,
template: `
<div>
<!-- 该试图容器没有 name 属性,则默认显示 default 指定的组件 Foo -->
<router-view class="view first"></router-view>
<!-- 该试图容器 name 属性指向 a,则显示 components 下 a 指定的组件 Bar -->
<router-view class="view second" name="a"></router-view>
<!-- 该试图容器 name 属性指向 b,则显示 components 下 b 指定的组件 Asd -->
<router-view class="view third" name="b"></router-view>
</div>
`,
});
/settings/emails /settings/profile
+-----------------------------------+ +------------------------------+
| UserSettings | | UserSettings |
| +-----+-------------------------+ | | +-----+--------------------+ |
| | Nav | UserEmailsSubscriptions | | +------------> | | Nav | UserProfile | |
| | +-------------------------+ | | | +--------------------+ |
| | | | | | | | UserProfilePreview | |
| +-----+-------------------------+ | | +-----+--------------------+ |
+-----------------------------------+ +------------------------------+
import Vue from 'vue';
import VueRouter from 'vue-router';
// inject Vue Router to Vue
Vue.use(VueRouter);
// components
const UserSettings = {
template: `
<div>
<!-- 使用引入的 Nav 组件 -->
<Nav/>
<router-view><router-view>
<router-view name="helper"><router-view>
</div>
`,
components: { Nav }, // 引入 Nav 组件,组件内容不是重点,可参考官网例子
};
const UserEmailsSubscriptions = { template: '<div>UserEmailsSubscriptions</div>' };
const UserProfile = { template: '<div>UserProfile</div>' };
const UserProfilePreview = { template: '<div>UserProfilePreview</div>' };
// Vue Router Configuration
const routes = [
{
name: 'settings',
path: '/settings',
component: UserSettings,
children: [
// 添加一个空路由,防止跳转至 /settings 路由时页面什么都不显示
{
name: 'default',
path: '',
component: UserEmailsSubscriptions,
},
{
name: 'emails',
path: 'emails'
component: UserEmailsSubscriptions,
},
{
name: 'profile',
path: 'profile',
components: {
default: UserProfile,
helper: UserProfilePreview,
},
],
];
//Vue Router instance
const router = new VueRouter({
routes,
});
// Vue instance
const app = new Vue({
router,
template: `
<div>
<router-view></router-view>
</div>
`,
}).$mount('#app');