Vue 路由

路由

这之前需要先安装 Vue 环境: 安装 vue-cli 环境,或者按照如下步骤安装

# 安装 vue 脚手架
npm install -g @vue/cli
# 安装 vue 路由
npm install vue-router -g

初始化一个 vue 环境,可以看上一篇文章 创建 vue-cli 新项目

vue init webpack demo01

然后进入文件并运行运行,查看是否创建成功

cd demo01
npm install
npm run dev

执行后出现如下内容,点击 http://localhost:8080 即可,进入页面

页面显示如下,即为执行成功

demo01 文件夹中为所有 vue 文件,进入 src 创建一个 page1.vuepage2.vue,代码内容如下:

page1.vue

<template>
  <h1>Page1页面</h1>
</template>

<script>
</script>

<style>
</style>

page2.vue

<template>
  <h1>Page2页面</h1>
</template>

<script>
</script>

<style>
</style>

然后再创建一个 router.js 内容

/* eslint-disable */
import Vue from 'vue';
//引入vue-router
import VueRouter from 'vue-router';
//第三方库需要use一下才能用
Vue.use(VueRouter)

import page1 from "./page1.vue"
import page2 from "./page2.vue"

const routes = [
  // 格式如下:{path:'/路径地址', component: 上面import导入的vue页面名字 }
  {path:"/page1", component: page1},
  {path:"/page2", component: page2},

  // 设置默认为page1页面
  {path:'',component:page1}
  // 或者初始重定向到 page1
  //{path:'', redirect: 'page1'}

]

const router = new VueRouter({
  routes
})

export default router

修改 App.vue 内容,添加 <div> 标签中添加路由链接,添加的内容为下面注释之后的四行代码,完整代码如下:

<template>
  <div id="app">
    <img src="./assets/logo.png">

    <!-- 添加两个路由链接 -->
    <div>
      <router-link to="/page1">Page1</router-link>
      <router-link to="/page2">Page2</router-link>
    </div>

    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

然后开始执行

npm run dev

然后点击进入链接:http://localhost:8080

动态路由

src 文件夹下创建一个 user.vue 文件,代码内容如下:

user.vue

<template>
  <!-- 这个 username 和 router.js 文件中的 /user/:username 冒号后面的名字要一样-->
  <h1>欢迎登陆 {{$route.params.username}}</h1>
</template>

<script>
</script>

<style>
</style>

router.js 文件中在其他几个 import 下面添加如下一行,导入 user.vue 文件

import user from "./user.vue"

然后在 const routes 常量中添加 user.vue 的动态路由链接路径

const routes = [
  // 格式如下:{path:'/路径地址', component: 上面import导入的vue页面名字 }
  {path:"/page1", component: page1},
  {path:"/page2", component: page2},
  {path:"/user/:username", component: user},

  // 重定向
  {path:'', redirect: 'page1'}
]

App.vue 中的 <div id='app'> 标签里添加如下代码

<div>
  <router-link to="/user/zhangsan">切换用户:zhangsan</router-link>
  <router-link to="/user/lisi">切换用户:lisi</router-link>
</div>

然后重新执行,点击下面的切换标签,

npm run dev


文件下载

Git :https://gitee.com/LaoDie1/vue-router

本站zip下载:demo01.zip

发表评论