从零开始学VUE之VueRouter(Vue-router基本使用)

使用Vue-router

创建组件

About.vue

<template>
  <div>
    <h2>this is about!</h2>
  </div>
</template>

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

<style scoped>

</style>

Home.vue

<template>
  <div>
    <h2>this is home!</h2>
  </div>
</template>

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

<style scoped>

</style>

在Index.js中添加映射规则

import Vue from 'vue'
// 导入路由
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

import home from '../components/Home'
import about from '../components/About'

// Vue加载
Vue.use(Router)

// 传入路由映射配置 导出路由实例
export default new Router({
  routes: [
    // {
    //   path: '/',
    //   name: 'HelloWorld',
    //   component: HelloWorld
    // },
    {
      path: '/home',
      name: 'home',
      component:home
    },
    {
      path: '/about',
      name: 'about',
      component:about
    },
  ]
})

在App.vue中添加导航

通过router-view展示

<template>
  <div id="app">
<!--    <img src="./assets/logo.png">-->
<!--    导航链接-->
    <router-link to="/home">主页</router-link>
    <router-link to="/about">关于</router-link>
<!--    用于展示组件-->
    <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>

效果

点击主页

点击关于

默认展示首页

增加index.js的配置

// 在默认的情况下 重定向到主页
    {
      path: '',
      redirect: "/home"
    },

默认跳转的uri是使用的hash方式,这样会留下history历史记录,也就是说可以通过浏览器的左右箭头控制前后跳转,并且路径中间会有#号

如果不希望存在#,可以设置模式为history

// 设置模式为 history
mode: 'history',

如果不希望存在浏览记录History可以将to 改为replace

可以在 router-link 中添加 replace 属性

作者:彼岸舞

时间:2021\06\28

内容关于:VUE

本文属于作者原创,未经允许,禁止转发

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值