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

1.9 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 动态路由匹配