Vue-cli项目中路由的基础用法,以及路由嵌套
生活随笔
收集整理的這篇文章主要介紹了
Vue-cli项目中路由的基础用法,以及路由嵌套
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文件目錄:
?
編輯router文件夾下的index.js文件
·?第一步:引用vue和vue-router ,Vue.use(VueRouter)
/* eslint-disable*/ import Vue from 'vue' import Router from 'vue-router' Vue.use(Router)·第二步:引用定義好的路由組件
import ChildOne from '../components/childOne' import ChildTwo from '../components/childTwo'?
·第三步:定義路由(路由對象包含路由名、路徑、組件、參數(shù)、子路由等),每一個路由映射到一個組件
·第四步:通過new Router來創(chuàng)建router實例
export default new Router({routes: [{path: '/one',name: 'ChildOne',component: ChildOne},{path: '/two',name: 'ChildTwo',component: ChildTwo}] })?
在main.js文件上編輯
·第五步:在main.js中將路由實例掛載到vue根實例上,使得整個應用都有路由功能,如下
import router from '../src/router/index.js' new Vue({el: '#app',router,components: { App },template: '<App/>' })?
在組件文件上使用路由,編輯app.vue
·第六步:在組件中使用router-link 標簽實現(xiàn)跳轉(zhuǎn)路由、使用router-view來實現(xiàn)路由顯示,如下
<template><div id="app"><div><img src="./assets/logo.png"></div><router-link to="/one">顯示第一個頁面</router-link><router-link to="/two">顯示第二個頁面</router-link><router-view></router-view></div> </template>該demo中的childOne.vue組件文件
<template><div style="border:1px solid blue;color:blue"><p>這是子組件1的內(nèi)容!!!</p><p>!!!這是第1個路由的頁面!!!</p></div> </template>childTwo.vue組件文件
<template><div style="border:1px solid blue;color:blue"><p>這是子組件2的內(nèi)容</p><p>這是第二個路由顯示的頁面怎么樣</p></div> </template>注意:在組件中可以使用this.$router訪問路由器,可以使用this.$route訪問當前路由;
實現(xiàn)效果:
?
路由嵌套:
使用方法:在router/index.js中定義路由對象時,使用children:[{...},{...}]的形式設置下級路由及映射組件,如下在one路由下設置了log和reg路由
export default new Router({routes: [{path: '/one',name: 'ChildOne',component: ChildOne,children:[{path:'log',component:Log,},{path:'reg',component:Reg,},],},{path: '/two',name: 'ChildTwo',component: ChildTwo}] })childOne.vue中使用二級路由
<template><div style="border:1px solid red;color:red;"><p>這是子組件1的內(nèi)容</p><p>下面開始點擊顯示嵌套的子路由 </p><router-link to="/one/log">顯示登錄頁面</router-link><router-link to="/one/reg">顯示注冊頁面</router-link><router-view></router-view></div> </template>總結(jié)
以上是生活随笔為你收集整理的Vue-cli项目中路由的基础用法,以及路由嵌套的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 趣学python3(38)--多项式最小
- 下一篇: tensorflow随笔 -tf.con