【Vue】vue-router 路由

一、什么是vue router

Vue Router 是 Vue.js (opens new window)官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。

包含的功能有:

  • 嵌套的路由/视图表

  • 模块化的、基于组件的路由配置

  • 路由参数、查询、通配符

  • 基于 Vue.js 过渡系统的视图过渡效果

  • 细粒度的导航控制

  • 带有自动激活的 CSS class 的链接

  • HTML5 历史模式或 hash 模式,在 IE9 中自动降级

  • 自定义的滚动条行为



二、vue router的安装

Vue Router是一个插件包,我们要使用,我们需要同npm/cnpm进行安装

注意:我们是基于vue-cli项目【点击查看】进行安装的


在的vue-cli项目【点击查看】下使用下面命令进行安装,或者直接使用IEDA的Terminal

命令:npm install vue-router --save-dev
在这里插入图片描述


可能会有问题,按照它给的提示进行修复
在这里插入图片描述

此时,在项目的node_modules目录下面,我们已经有vue-router
在这里插入图片描述



三、vue router的使用


原理图
在这里插入图片描述


在vue中使用import VueRouter from 'vue-router'将vue router导入。

如果在一个模块化工程中使用它,必须要通过 Vue.use() 明确地安装路由功能:

import Vue from 'vue'
import VueRouter from 'vue-router'

//显式的声明使用VueRounter
Vue.use(VueRouter)

下面,我来写一个简单的例子

第一步:依赖组件的搭建

首先,我们需要编写一个Main.vue组件(主页)和一个Content.vue组件(内容页)用于跳转的演示。

Main.vue

<template>
    <h3>欢迎来到,寒江の首页</h3>
</template>

<script>
    export default {
        name: "Main"
    }
</script>

<style scoped>

</style>

Content.vue

<template>
  <h3>欢迎来到,寒江の内容页</h3>
</template>

<script>
    export default {
        name: "content"
    }
</script>

<style scoped>

</style>

App.vue

<template>
    <div id="app">
      <h2>欢迎来到,寒江のvue-router世界</h2>
      <router-link to="/show/main">首页</router-link>
      <router-link to="/show/content">内容页</router-link>
      <router-view></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>


第二步:路由配置文件的创建于配置

我们遵守所有的路由写在一个路由的配置文件中,我们需要创建一个router文件夹,并在该文件夹下创建index.js(index.js其实就是router的配置文件,官方建议命名成index.js,第三步1中会说明为什么)
在这里插入图片描述

1、路由的显式声明使用

我们要是index.js中使用vue-router,需要如下声明

import Vue from 'vue'
import VueRouter from 'vue-router'

//使用vue-router
Vue.use(VueRouter);

2、路由配置的容器

在index.js中的路由配置,我们需要写在如下的配置中

export default new VueRouter({
  routes:[
    {
      path:'',  //路由的路径
      name: '',  //路由名
      component: ...  //跳转到的组件
    }
  ]
})

3、路由配置的具体实现

我们来配置跳转Main.vue的设置,我们用到了Main.vue,所以需要引入

import Main from "../components/Main";

编写路由配置

  routes:[
    {
      path:'/main',
      name: 'main',
      component: Main
    },
  ]

我们来配置跳转Content.vue的设置,我们用到了Content.vue,所以需要引入
import Content from "../components/Content";

编写路由配置

  routes:[
    {
      path:'/content',
      name: 'content',
      component: Content
    },
  ]

4、上述关于index.js的整合

import Vue from 'vue'
import VueRouter from 'vue-router'

import Content from "../components/Content";
import Main from "../components/Main";

//使用vue-router
Vue.use(VueRouter);

//配置导出路由
export default new VueRouter({
  routes:[
    {
      //路由的路径
      path:'/content',
      name: 'content',

      //跳转的组件
      component: Content
    },
    {
      //路由的路径
      path:'/main',
      name: 'main',

      //跳转的组件
      component: Main
    }
  ]
})

第三步:在App.vue中使用路由

1、在main.js中导入路由

因为main.js是与App.vue向绑定的,如果我们要是在App.vue中#app使用index.js配置好的路由,那么我们需要将index.js引入main.js。

import router from './router' //自动的扫描router下的index

这也是为什么官方推荐我们使用index.js作为路由配置名的原因。

现在我们在main.js中引入了index.js,但是需要配置路由,方法很简单,如下:
在这里插入图片描述


2、在App.vue中实现vue-router

介绍两个新的标签

< router-link to=“路由路径”>:其作业就相当于是html中的< a>标签

< router-view>:当点击< router-link to=“路由路径”>时,相关组件的内容将会显示在< router-view>所在的位置,起到定位显示组件。

<template>
  <div id="app">
    <h2>欢迎来到,寒江のvue-router世界</h2>
    
    <router-link to="/main">首页</router-link>
    <router-link to="/content">内容页</router-link>
    <router-view></router-view>
    
  </div>
</template>

运行命令: npm run dev
我们可以发现,并没有默认显示页
在这里插入图片描述


3、设置< router-view>的默认显示组件

我只需要在index.js中的routes中加上如下代码即可

    {
      //默认路径
      path:'/',
      name: 'main',
      component: Main
    },

在这里插入图片描述


这里有一个下细节需要注意一下,如果将内容写在 < div id="app">的外面,那么…
在这里插入图片描述



四、路由嵌套

实际生活中的应用界面,通常由多层嵌套的组件组合而成。同样地,URL 中各段动态路径也按某种结构对应嵌套的各层组件,例如:
在这里插入图片描述

由上图,我们可知,路由嵌套的应用在开发中最长见的就是在显示页面与导航栏的关系了。


1、语法

路由嵌套的语法很简单,如下:

children:其为路由嵌套的关键字,写在路由A的children属性中的路由,即为A的嵌套路由

const router = new VueRouter({
  routes: [
    {
      path: '/user/:id',
      component: User,
      children: [
        {
          // 当 /user/:id/profile 匹配成功,
          // UserProfile 会被渲染在 User 的 <router-view> 中
          path: 'profile',
          component: UserProfile
        },
        {
          // 当 /user/:id/posts 匹配成功
          // UserPosts 会被渲染在 User 的 <router-view> 中
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
})

注意事项:在children中的path的开始是没有/,比如path:"/next/cont"是不对的,path:"next/cont"是对的。


2、实例

我们做一个小例子,将“三”中的例子改成路由嵌套的形式…

原本的Content组件和Main组件不需要改变…

我们需要新添加两个组件:一个是用于展示Content和Main组件的Show组件,另一个是“Error404组件”。

Show.vue

<template>
    <div>
      <h2>欢迎来到,寒江のvue-router世界</h2>
      <router-link to="/show/main">首页</router-link>
      <router-link to="/show/content">内容页</router-link>
      <router-view></router-view>
    </div>
</template>

<script>
    export default {
        name: "Show"
    }
</script>

<style scoped>

</style>

Error.vue

<template>
  <div>
    <div class="main">
      抱歉,你的页面走丢了!
    </div>
    请访问:<a href="http://localhost:8080/#/show">http://localhost:8080/#/show</a>
  </div>
</template>

<script>
    export default {
        name: "Error"
    }
</script>

<style scoped>
.main{
  width: 500px;
  height: 200px;
  margin: 100px auto;
  line-height: 200px;
  align-content: center;
  font-size: 25px;
}
</style>

我们还需要改动一下App.vue中的模版

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

对应的路由配置文件 index.js

import Vue from 'vue'
import VueRouter from 'vue-router'

import Content from "../components/Content";
import Main from "../components/Main";
import Show from "../components/Show";
import Error from "../components/Error";

//使用vue-router
Vue.use(VueRouter);

//配置导出路由
export default new VueRouter({
  mode: history,
  routes:[
    {
      path:'/show',
      name:'show',
      component:Show,
      children:[
        {
          path:'content/:author/:info',
          name: 'content',
          component: Content,
          props: true
        },
        {
          path:'main/:author/:info',
          name: 'main',
          component: Main,
          props: true
        }
      ]
    },
    { //404路由配合
      path:'*',
      name: 'error',
      component: Error
    }
  ]
})


3、效果展示

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述


4、原理图

这样我们的代码就弄完了,你是不是觉得有点懵逼,说实话,我在开始整理的时候是很懵逼的,感觉乱糟糟的,这个套哪个,哪个套这个… 不要代码我给大家花了一张图:
在这里插入图片描述



五、参数传递与重定向

到此,我们还没有进行传值操作,目前只是解决了页面(组件)的 跳转…,下面我们将解决参数传递与重定向。


1、参数传递

第一种方式:耦合性较高

:to:首先要先绑定route-link的参数to,to中的值是对象。

name:’’:值得注意的是,这里的name是指路由配置中的name,而不是组件的name,将会将参数传递给对应的组件。

params:{}:其中写参数,通过键值对的形式书写。

 <router-link :to="{name:'main', params:{author:'寒江', info:'首页'}}">首页</router-link>
 <router-link :to="{name:'content',params: {author:'寒江', info:'内容页'}}">内容页</router-link>


/:参数名这里的参数名要和上面的params中的参数名相同。其作用是在url中显示专递的值,类似于get请求;也可不不写,那么就相当于post请求。

    {
      path:'/show',
      name:'show',
      component:Show,
      children:[
        {
          path:'content/:author/:info',
          name: 'content',
          component: Content
        },
        {
          path:'main/:author/:info',
          name: 'main',
          component: Main
        }
      ]
    },

{{$route.params.参数名}}:取出参数名对应的参数值。

<template>
  <h3>欢迎来到,{{$route.params.author}}の{{$route.params.info}}</h3>
</template>

在这里插入图片描述
在这里插入图片描述


第二种方式:一种相对解耦的形式(推荐)

props: true:其作用是声明通过route-link传递的参数是可以在相对应的组件中通过props属性进行接收,当然组件中的属性名要和参数名相同

    {
      path:'/show',
      name:'show',
      component:Show,
      children:[
        {
          path:'content/:author/:info',
          name: 'content',
          component: Content,
          props: true
        },
        {
          path:'main/:author/:info',
          name: 'main',
          component: Main,
          props: true
        }
      ]
    },

props:[‘author’,‘info’]:用于绑定接收传递过来的参数。

<template>
    <h3>欢迎来到,{{author}}の{{info}}</h3>
</template>

<script>
    export default {
        name: "Main",
        props:['author','info']
    }
</script>

<template>
  <h3>欢迎来到,{{author}}の{{info}}</h3>
</template>

<script>
    export default {
        name: "Content",
        props:['author','info']
    }
</script>

在这里插入图片描述


2、重定向

在vue中实现重定向不要太简单,重定向会导致地址栏(url)发生改变…


配置重定向(index.js:路由的配置文件)

当访问http://localhost:8080/#/geback时,会自定跳转到http://localhost:8080/#/show

    {
      path:'/goback',
      redirect:'/show'
    }

在这里插入图片描述
在这里插入图片描述


六、路由的模式与路由钩子

1、路由的模式

路由有两种模式

  • hash(默认):路径带 # 号,例如:http://localhost/#/show
  • history:路径不带 # 号,例如:http://localhost/show
export default new VueRouter({
  mode: history,
  routes:[
    ...
  ]
})

2、路由钩子

安装:Axios

npm install --save axios vue-axios

将下面代码加入入口文件:

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

介绍两个路由相关的钩子

进入路由之前的钩子…

beforeRouteEnter:(to, from, next)=>{ 
... 
next(...);
}

进入路由之后的钩子…

beforeRouteLeave:(to, from, next)=>{
 ... 
 next(...);
 }

参数解释:

to:路由将要跳转的路径信息

from:路由跳转前的路径信息

next:路由的控制参数

            next() :跳到下一个页面

             next(’/path’) :路由的跳转方向,使其跳转到另一个路由

            next(false) :返回原来页面

             next((vm)=>{}) : 仅在beforeRouteEnter中使用,vm是组件实例


下面举一个例子,在进入路由之前,获取data.json文件中的数据
第一步:创建一个Data.vue组件
1.在data()中编写一个与json字符串格式相同的对象info

data(){
            return{
                //格式要和json一致
                info:{
                    title:null,
                    url:null,
                    classify:{
                        name01:null,
                        name02:null,
                        name03:null,
                        name04:null
                    },
                    links:[
                        {
                            title:null,
                            url:null
                        },
                        {
                            title:null,
                            url:null
                        },
                        {
                            title:null,
                            url:null
                        },
                        {
                            title:null,
                            url:null
                        }
                    ]
                }
            }
        }

2.利用Axios编写一个getData方法,或者json文件

this.info=res.data:将获取到的数据res赋值给data()中的info,因为info与与json字符串格式相同,所以可以直接赋值

        methods:{
            getData:function () {
                this.axios.get('../../static/json/data.json').then((res)=>{
                    console.log(res)
                    this.info=res.data
                }).catch((error)=>{
                    console.log(error)
                })
            }
        },

3.编写beforeRouteEnter和beforeRouteLeave方法

        beforeRouteEnter:(to, from, next) => {
            console.log("进入路由之前...")
            next((vm)=>{
                vm.getData()
            })
        },
        beforeRouteLeave:(to, from, next) => {
            console.log("进入路由之后...")
            next()
        },

4.编写模板

<template>
  <div>
    <h2>{{info.title}}:<a :href=info.url>{{info.url}}</a></h2>
    <div>
      <h3 v-for="item in info.links">
        {{item.title}}:<a :href=item.url>{{item.url}}</a>
      </h3>
    </div>
  </div>
</template>

整合

<template>
  <div>
    <h2>{{info.title}}:<a :href=info.url>{{info.url}}</a></h2>
    <div>
      <h3 v-for="item in info.links">
        {{item.title}}:<a :href=item.url>{{item.url}}</a>
      </h3>
    </div>
  </div>
</template>

<script>
    export default {
        name: "Data.vue",
        methods:{
            getData:function () {
                this.axios.get('../../static/json/data.json').then((res)=>{
                    console.log(res)
                    this.info=res.data
                }).catch((error)=>{
                    console.log(error)
                })
            }
        },
        beforeRouteEnter:(to, from, next) => {
            console.log("进入路由之前...")
            next((vm)=>{
                vm.getData()
            })
        },
        beforeRouteLeave:(to, from, next) => {
            console.log("进入路由之后...")
            next()
        },
        data(){
            return{
                //格式要和json一致
                info:{
                    title:null,
                    url:null,
                    classify:{
                        name01:null,
                        name02:null,
                        name03:null,
                        name04:null
                    },
                    links:[
                        {
                            title:null,
                            url:null
                        },
                        {
                            title:null,
                            url:null
                        },
                        {
                            title:null,
                            url:null
                        },
                        {
                            title:null,
                            url:null
                        }
                    ]
                }
            }
        }
    }
</script>

<style scoped>

</style>

第二步:创建相关路由信息

我们依然将Data.vue的路由作为Show.vue的子路由(index.js)

        {
          path:'data',
          name:'data',
          component:Data
        }

第三步:更新Show.vue的组件

添加一个route-link

      <router-link to="/show/data">数据页</router-link>

点击“数据页”之后的效果
在这里插入图片描述

点击“返回”之后的效果
在这里插入图片描述



vue-router文档:https://router.vuejs.org/zh/installation.html/

axios文档:http://www.axios-js.com/zh-cn/docs/vue-axios.html


你爱我,我会陪你;你不爱我,我给你自由。这就是傻傻的我,那个在乎你的我…
请添加图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3 中,你可以使用 Vue Router 进行由跳转。下面是一些基本的步骤: 1. 首先,确保你已经安装了 Vue Router。你可以通过运行以下命令来安装它: ``` npm install vue-router@next ``` 2. 在你的主文件(例如 `main.js` 或 `main.ts`)中导入 Vue Router 和你的由配置: ```javascript import { createApp } from 'vue'; import { createRouter, createWebHistory } from 'vue-router'; import App from './App.vue'; import Home from './views/Home.vue'; import About from './views/About.vue'; const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ]; const router = createRouter({ history: createWebHistory(), routes }); const app = createApp(App); app.use(router); app.mount('#app'); ``` 在上面的示例中,我们创建了两个由:`/` 对应 `Home` 组件,`/about` 对应 `About` 组件。你可以根据自己的需求添加更多的由。 3. 在你的组件中使用由跳转,你可以使用 `<router-link>` 组件或 `$router.push` 方法。 使用 `<router-link>` 组件: ```html <router-link to="/">Home</router-link> <router-link to="/about">About</router-link> ``` 使用 `$router.push` 方法: ```javascript // 在方法中调用 methods: { goToHome() { this.$router.push('/'); }, goToAbout() { this.$router.push('/about'); } } // 或者在模板中调用 <button @click="$router.push('/')">Go to Home</button> <button @click="$router.push('/about')">Go to About</button> ``` 这样,当用户点击链接或按钮时,由就会进行跳转。 这只是一个基本的示例,你还可以使用更多的 Vue Router 功能,如由参数、嵌套由、由守卫等。你可以参考 Vue Router 的官方文档来了解更多信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值