Vue之vue项目中实现vue-router路由跳转

  • 如我们所知,vue是一个大型的单页面应用,它实际上可以看成是只有一个页面,那么很多人会问,不同页面的切换该如何做处理?

  • 没错,靠的就是路由跳转vue-router了;

  • vue项目中的路由跳转有很多种方式,以下且听我细细说来~

1、首先,vue项目中应该先配置好Vue-Router,才能使用它:
  • 我们使用vue-cli创建项目的时候,在执行vue init webpack {项目名}命令的时候,有一项是可以选择是否要安装vue-router,如果选择yes,那么当时就会安装,如果选择no的话,就需要自己安装了;
  • 手动安装的步骤如下:
    先安装依赖:
npm install vue-router -D

安装完成后,在 src 文件夹下,创建一个 routers.js 文件,在该文件中引入所需的组件,创建 routers 对象:

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

export default new Router({ 
 routes: [
   {
     path: '/',   //path配置路由的路径
     name: 'HelloWorld',    //映射的组件所对应的name
     component: HelloWorld   //配置映射的组件
   }
 ]
})

最后再src/main.js中引入Vue-Router:

import router from './router'
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

此外,Vue-Router可以有相关的配置,在src/main.js中设置router:
mode属性:如果不配置 mode,就会使用默认的 hash 模式,该模式下会将路径格式化为 #! 开头;添加 mode: ‘history’ 之后将使用 HTML5 history 模式,该模式下没有 # 前缀,而且可以使用 pushState 和 replaceState 来管理记录。

const router = new VueRouter({
  mode: 'history',
  routes: routers
})
2、路由跳转的方式
(1)<router-view>

<router-view>用来渲染通过路由映射过来的组件,当路径更改的时候,<router-view>显示的内容也会更改。
在项目中,根组件是app.vue。app.vue的部分代码如下:

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

而如果页面中有固定的部分如导航栏或者页脚,则可以如上代码中所写,导航栏和页脚是不会变的,而中间的<router-view>部分则会随着路由的变化而变化。
呃呃呃~跑远了,绕回来
我们知道,Vue项目中有父组件和子组件,子组件都会按需渲染到父组件的<router-view>中,此时便需要<router-view>的嵌套,体现在router.js文件中:

 {
      path: '/home',
      name: 'homePage',
      component: homePage,
      children:[
        {
          path: '/index1',
          name: 'component_1',
          component: component_1
        },
        {
          path: '/index2',
          name: 'component_2',
          component: component_2
        }
      ]
    }
(2)使用<router-link>映射路由

我想从homePage页面跳转到flexExample页面:

<template>
   <div id="main">
     <router-link to="/flex">跳转到flexExample页面</router-link>
   </div>
</template>

页面显示如下,采用<router-link>显示的是文本链接可成功跳转
在这里插入图片描述

(3)通过添加click方法跳转页面

同样需求,从homePage页面跳转到flexExample页面

<template>
   <div id="main">
     <el-button type="primary" @click="toFlexExamplePage">
     flex弹性布局</el-button>
   </div>
</template>
<script>
export default {
  name: 'home-page',
  methods:{
    toFlexExamplePage:function(){
      this.$router.push({
        path:'/flex'
      })
    }
  }
}
</script>

参考文章:https://www.cnblogs.com/wisewrong/p/6277262.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值