vue-router路由使用

使用npm通过webpack模板创建vue工程后,会发现以下几个东西:
1、router目录下有个index.js文件
2、App.vue文件内容里面有个< router-view />标签

index.js里面Router具体路由的定义,如下格式:

xport default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/index/:id',
      name: 'Index',
      component: Index,
      children: [
        // 当 /index/:id 匹配成功,
        // UserHome 会被渲染在 Index 的 <router-view> 中
        { path: '', component: UserHome },

        // ...其他子路由
      ]
    }
  ]
})

这个是对具体路由路径的组件映射关系的对应。
上面提到的< router-view />标签就是根据这个路由映射的定义装载当前路径vue组件。

通过标签跳转

首先要提到的是< router-link>标签,通过这个标签可以进行相应跳转

<router-link to="/index">跳转</router-link>
<!-- 上面这句话意思是使< router-view />标签展示与/index路径相映射的组件 -->

<router-link to="/index" replace>跳转</router-link>
<!-- 上面这句话意思也是使< router-view />标签展示与/index路径相映射的组件,但与第一个的区别是不会留下history -->

<router-link to="index" append>跳转</router-link>
<!-- 上面这句话意思也是使< router-view />标签展示在当前路径上追加index路径后与之映射的vue组件 这个一般是用于嵌套路由,配置方法参考上面路由格式第二个 -->

通过方法跳转

路由跳转主要通过router类的几个方法来进行。
主要为push,replace,go 三个方法

//router.push(location)=====window.history.pushState
//功能与上面router-link标签默认值相同
this.$router.push(path);

//router.replace(location)=====window.history.replaceState
//功能与上面router-link标签添加replace属性作用相同
this.$router.replace(path);

//router.go(n)====window.history.go
//功能为根据输入值向前或向后跳转n个历史记录
this.$router.go(n);

如何将相应js方法挂载到全局使用参考:
https://blog.csdn.net/qq_36666651/article/details/80302560

猜你喜欢

转载自blog.csdn.net/qq_36666651/article/details/80302843