12.3 vue-router的应用示例
如果用Vue Cli脚手架创建项目,就不需要下载vue-router,否则需要执行:npm install vue-router --save 来安装。
下面我们用回溯的方式来展现vue-router示例,由表及里,先看整体逻辑,如图12.3-1:
图12.3-1
1、App.vue的代码
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view/>
</div>
</template>
router-link是路由指向,router-view是渲染组件的占位符。
2、路由表(router/index.js),如图12.3-2对index.js做了一下解释:
图12.3-2
3、组件(views/about.vue)
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
以上代码可由Vue Cli脚手架自动生成,通过路由表把about组件渲染到app组件的router-view区域。
----------------------------------------------------------------------------------------------------------------
本内容为《抹平Vue学习曲线》的部分章节,需要阅读完整书籍的,可以跟作者沟通。
----------------------------------------------------------------------------------------------------------------