1.在相关页面使用router-link (其中的to中的内容是指转向的页面)
2.在components文件下添加A.vue 和B.vue 文件(在其他文件下添加也可以,只要修改后面路径就好)
3.在index.js 文件中导入相关路径 (import … from …)
4.并在index.js文件中填写相关path:
5.成功展示
6.设置返回(rounter-link的to处只要填写 / 就可以返回到首页)(可要可不要)
使用路由和a标签的区别:
标签定义超链接,用于从一张页面链接到另一张页面。通过a标签进行跳转,页面会被重新渲染,即相当于重新打开一个新的网页,体现为视觉上的“闪烁”(如果是本地的项目基本看不出来)。
组件支持用户在具有路由功能的应用中 (点击) 导航。 通过 to 属性指定目标地址,默认渲染成带有正确链接的 标签,可以通过配置 tag 属性生成别的标签.。通过 router-link 进行跳转不会跳转到新的页面,也不会重新渲染,它会选择路由所指的组件进行渲染,避免了重复渲染的“无用功”。
对比,router-link组件避免了不必要的重渲染,它只更新变化的部分从而减少DOM性能消耗。
相关文件的代码
first.vue
<template>
<div>
<router-link to="/a">转向A页面 </router-link>
<router-link to="/b">转向B页面</router-link>
</div>
</template>
A.vue
<template>
<div>
<p>AAAAA</p>
<router-link to="/">返回</router-link>
</div>
</template>
B.vue
<template>
<div>
<p>BBBBB</p>
<router-link to="/">返回</router-link>
</div>
</template>
APP.vue
<template>
<div id="app">
<div>
<img src="./assets/logo.png">
</div>
<router-view/>
</div>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
#nav {
padding: 30px;
}
#nav a {
font-weight: bold;
color: #2c3e50;
}
#nav a.router-link-exact-active {
color: #42b983;
}
</style>
index.js (文件中的路径要修改为自己的目录下的文件)
import Vue from 'vue'
import VueRouter from 'vue-router'
import First from '../components/first.vue'
import A from '../components/A.vue'
import B from '../components/B.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'First',
component: First
},
{
path:'/a',
component:A
},
{
path:'/b',
component:B
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
我的文件目录