vue-router--默认路径和router-link的其他属性以及代码实现

1,313 阅读1分钟

默认路径

就是当你的网页一进去你希望显示首页的内容,可以通过这种方式实现. 在配置映射关系的时候,可以这样配置。

当刚进网页的path就是空的时候,它会重定向(redirect)到/home.

切换模式

vouter-link改变url的原理无非就是使用location.hash或是使用history模式。它默认是使用location.hash模式: 怎么切换成history模式呢?
很简单,在生成路由实例的时候添加:

router-link的其他属性

tag属性

<router-link  tag="li"></router-link>

router-link默认是被渲染成a标签,但是你可以通过tag属性设置它渲染成什么标签。比如li标签。

replace属性

<router-link  replace></router-link>

如果router-link使用history模式,默认是使用pushState形式,这样每次的path会形成一个栈结构,所以可以使用浏览器上的前进后退。那么怎么切换成replaceState呢?就是添加这个replace属性

active-class属性

router-link会给被选中的元素添加一个类router-link-active.你可以通过active-class属性重命名这个类名。 tips:可以在路由实例中,设置一个属性linkActiveClass,这样所有的active-class都会被命名成linkActiveClass的值。

通过代码实现url的更改

怎么实现用代码改变url而不刷新页面呢?我们一开始想到的肯定是使用location.hash或者是history模式,但是现在我们有了vue-router最好使用vue-router给我们提供的方法。
vue-router的源码给我们所有的组件都添加了一个属性$router,$router属性有一个push方法就可以通过push方法修改url.它对应的是history模式中的pushState方法。举一反三,$router属性还有一个replace方法对应的就是history模式中的replaceState方法。他们的区别是有无缓存记录,能不能返回前进
那么现在我们可以用代码实现一下router-link的作用。

<template>
  <div id="app">
    <!-- <router-link to="/home" replace>首页</router-link>
    <router-link to="/about" replace active-class="aaa">关于</router-link> -->
    <li @click="goHome">首页</li>
    <li @click="goAbout">关于</li>
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App',
  methods:{
    goHome()
    {
      this.$router.push("/home");//每个组件都有$router属性
    },
    goAbout()
    {
      this.$router.push("/about");
    }
  }
}
</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>