要理解Vue的router,首先我们就要先理解2个单词
1.routes 这里就是一个路由的规则 带S 说明是多个路由规则,主要作用是定义路径和对应的component组件
2.router 就是路由器。它的作用就是根据routes的规则去执行分发
首先先要定义一个路由规则 routes
const myroutes=[
{path:'/foo',component:{template:"<b>FOO</b>"}},
{path:'/bar',component:{template:"<b>BAR</b>"}}
]
路由规则定义完毕:path 就是路径 component 表示目标组件
其次要声明初始化一个路由器 router
const router=new VueRouter({
routes:myroutes
})
这里需要讲解下:routes:routes routes 是构造器里面的路由规则对象 myroutes 是我们设计的路由器规则
此时 我们得到了一个router 路由器 现在我们要挂在到对应的对应的vue实例中
<script>
new Vue({
el:"#app",
data:{},
router:router
})
</script>
就这样子, 执行就会成功! 显示结果
完整的代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<title>Vue-router</title>
</head>
<body>
<div id="app">
<h1>Hello App!</h1>
<p>
<a href="#/foo">首页 </a>
<router-link to="/bar">邮箱 </router-link>
</p>
<router-view></router-view>
</div>
<script type="text/javascript">
//首先定义路由规则
const myroutes=[
{path:'/foo',component:{template:"<b>这是首页内容:www.nasiot.com</b>"}},
{path:'/bar',component:{template:"<b>这是邮箱内容:admin@nasiot.com</b>"}}
]
//初始化路由
const router=new VueRouter({
routes:myroutes
})
new Vue({
el:"#app",
data:{},
router:router
})
</script>
</body>
</html>
南宁点餐小程序:www.nasiot.com