Files
note/2019/12/vue-router.md
2019-12-09 09:58:31 +08:00

2.6 KiB
Raw Blame History

安装 vue-router

yarn add vue-router

准备用vue-cli 新建文件

1.终端打开你当前目录 vue create +项目名

2.把 src/App.vue 文件重写为空白模板

3.在src/components目录下新建两个组件a,b

  1. 在src/main.js 里引入 vue-router

import VueRouter from 'vue-router'

注册使用:

Vue.use(VueRouter)

正式使用 vue-router

1.在src/main.js中 定义 路径及映射的组件

const routes= [
  { path: "/a", component: aa },
  { path: "/b", component: bb },

]

2.实例化 VuRouter

const router = new VueRouter({
  routes // (缩写) 相当于 routes: routes
})

3.渲染 1 在src/main.js中

new Vue({
  el: '#app',
  router,
  render: h => h(App)
})


2 在src/app.vue 中 的id为 app 的div内部写入 router-view标签

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

全部代码:

app.vue

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

<script>
  
</script>

<style>
</style>


main.js

import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
import aa from "./components/a.vue";
import bb from "./components/b.vue";
Vue.use(VueRouter) 
Vue.config.productionTip = false

const routes= [
  { path: "/a", component: aa },
  { path: "/b", component: bb },

]
const router = new VueRouter({
  routes // (缩写) 相当于 routes: routes
})

new Vue({
  el: '#app',
  router,
  render: h => h(App)
})


a.vue


<template>
  <div class="hello">
   <div>这是aaa</div>
  </div>
</template>

<script>
export default {
  name: 'aa',

}
</script>


<style scoped>

</style>


b.vue (组件b)

<template>
  <div>
      <div>这是bbb</div>
  </div>
</template>

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

<style>

</style>

vuerouter 动态路由匹配

1.定义: 把匹配到的部分或全部路由,全都映射到一个组件

2.使用: 动态路径参数 用: 开头

1在main.js 的路由定义中:

{ path: "/a", component: aa },

修改为:

{ path: "/a/:参数名", component: 映射的组件名 },

2 在映射的组件中获取传入的动态参数的值

在引入的组件中 使用 {{ $route.params.参数名}} 获取参数的值

2.注: 当使用路由参数时,映射的组件会重复使用,都渲染相同组件,比起销毁再创建,速度会更快

但是,组件挂载的事件不会重复调用

如果要检测页面跳转只能用watch 监听 $route对象或者使用beforeRouteUpdate 导航守卫