vue-router2.0的最简单的例子
程序员文章站
2022-04-13 08:48:46
...
对于对vue-router2.0没有任何概念的人来说,就算官网的代码是很直白片段都会有很大的困难,作为过来人贴出我的代码,为新手们做点贡献,
废话不说,看代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>这是一个 vue html</title>
<!--1. 引入vue-router-->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- 使用 router-link 组件来导航. -->
<!-- 通过传入 `to` 属性指定链接. -->
<!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
<!--3. 创建跳转的触发链接 -->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<!--4. 创建触发后页面显示的位置出口-->
<router-view></router-view>
</div>
<body>
<script>
// 2. 定义(路由)组件。
const Foo = {template:'<div>foo</div>'}
const Bar = {template:'<div>bar</div>'}
// 5. 定义路由,创建映射关系
const routes = [
{path:'/foo',component:Foo},
{path:'/bar',component:Bar}
]
// 6. 创建 router 实例,然后传 `routes` 配置
const router = new VueRouter({
routes // (缩写)相当于 routes: routes
})
// 7. 创建Vue对象并且挂载router到根实例。
const app = new Vue({
router
}).$mount('#app')
</script>
</html>
代码中注释详细说明了创建一个vue-router需要的步骤。