去官网学习→介绍 | Vue Router
cd 到项目 安装 Router : cnpm install --save vue-router
或着 创建项目时勾选Router vue create vue-demo
<i> to invert selection, and <enter> to proceed)
(*) Babel
( ) TypeScript
(*) Progressive Web App (PWA) Support
>(*) Router
( ) Vuex
( ) CSS Pre-processors
( ) Linter / Formatter
( ) Unit Testing
( ) E2E Testing
运行示例:
代码:index.js
// import { createRouter, createWebHashHistory } from 'vue-router'
import { createRouter, createWebHistory } from 'vue-router'
//主页资源
import HomeView from '../views/HomeView.vue'
//页面资源
const routes = [
{
//一级导航 首页
path: '/',
name: 'home',
component: HomeView
},
{
//一级导航 关于
path: '/about',
name: 'about',
//重定向 默认跳转到info
redirect:"/about/info/重定向默认数据",
//异步加载资源
component: () => import('../views/AboutView.vue'),
//二级导航
children:[
{
//传递数据 /:name key about/us/数据
path:"us/:name",
// 跳转的资源视图
component: () => import('../views/AboutUs.vue'),
},
{
// 传递数据 /:cont key about/info/数据
path:"info/:cont",
component: () => import('../views/AboutInfo.vue'),
}
]
}
]
const router = createRouter({
/**createWebHashHistory()
* http://127.0.0.1:8080/#/
* http://127.0.0.1:8080/#/about
*
* createWebHistory()
* http://127.0.0.1:8080
* http://127.0.0.1:8080/about
*
*/
history: createWebHistory(),
routes
})
//导出 router 在main.js 中引用
export default router
代码:AboutInfo.vue
<template>
<h2>关于信息</h2>
<!-- $route.params.cont 之前的 key /:cont -->
<p>获取到数据:{{$route.params.cont}}</p>
</template>
代码:AboutUs.vue
<template>
<h2>关于我们</h2>
<!-- $route.params.name 之前的 key /:name -->
<p>动态传递的数据:{{$route.params.name}}</p>
</template>
代码:AboutView.vue
<template>
<nav>
<!-- 跳转页面 动态传递数据 张三丰 -->
<router-link :to="'/about/us/' + userName ">关于我们</router-link> |
<!--跳转页面 传递数据 123456 -->
<router-link to="/about/info/123456">关于信息</router-link>
</nav>
<!-- 下一级 显示入口-->
<router-view/>
</template>
<script>
export default{
name: 'AboutView',
data(){
return{
userName:"张三丰"
}
}
}
</script>
代码:HomeView.vue
<template>
<p>首页-页面</p>
<router-link to="/about">跳转到关于页面</router-link>
</template>
代码:App.vue
<template>
<img alt="Vue logo" src="./assets/logo.png">
<nav>
<router-link to="/">首页</router-link> |
<router-link to="/about">关于</router-link>
</nav>
<!-- 下一级 显示入口-->
<router-view/>
</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>
代码:main.js
import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
//引入
import router from './router'
//.use(router)
createApp(App).use(router).mount('#app')