国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網(wǎng)站 > 幫助中心 > 正文

使用Vue-Router 2實(shí)現(xiàn)路由功能實(shí)例詳解

2024-07-09 22:41:22
字體:
供稿:網(wǎng)友

vue-router是Vue.js官方的路由插件,它和vue.js是深度集成的,適合用于構(gòu)建單頁面應(yīng)用。vue的單頁面應(yīng)用是基于路由和組件的,路由用于設(shè)定訪問路徑,并將路徑和組件映射起來。傳統(tǒng)的頁面應(yīng)用,是用一些超鏈接來實(shí)現(xiàn)頁面切換和跳轉(zhuǎn)的。在vue-router單頁面應(yīng)用中,則是路徑之間的切換,也就是組件的切換。

注意:vue-router 2只適用于Vue2.x版本,下面我們是基于vue2.0講的如何使用vue-router 2實(shí)現(xiàn)路由功能。

推薦使用npm安裝。

npm install vue-router

一、使用路由

在main.js中,需要明確安裝路由功能:

import Vue from 'vue'import VueRouter from 'vue-router'import App from './App.vue'Vue.use(VueRouter)

1.定義組件,這里使用從其他文件import進(jìn)來

import index from './components/index.vue'import hello from './components/hello.vue'

2.定義路由

const routes = [ { path: '/index', component: index }, { path: '/hello', component: hello },]

3.創(chuàng)建 router 實(shí)例,然后傳 routes 配置

const router = new VueRouter({ routes})

4.創(chuàng)建和掛載根實(shí)例。通過 router 配置參數(shù)注入路由,從而讓整個(gè)應(yīng)用都有路由功能

const app = new Vue({ router, render: h => h(App)}).$mount('#app')

經(jīng)過上面的配置之后呢,路由匹配到的組件將會(huì)渲染到App.vue里的<router-view></router-view>

那么這個(gè)App.vue里應(yīng)該這樣寫:

<template> <div >  <router-view></router-view> </div></template>

index.html里呢要這樣寫:

<body> <div ></div></body>

這樣就會(huì)把渲染出來的頁面掛載到這個(gè)id為app的div里了。

二、重定向 redirect

const routes = [ { path: '/', redirect: '/index'},  // 這樣進(jìn)/ 就會(huì)跳轉(zhuǎn)到/index { path: '/index', component: index }]

三、嵌套路由

const routes = [ { path: '/index', component: index,  children: [   { path: 'info', component: info}  ]  }]

通過/index/info就可以訪問到info組件了

四、懶加載

const routes = [ { path: '/index', component: resolve => require(['./index.vue'], resolve) }, { path: '/hello', component: resolve => require(['./hello.vue'], resolve) },]

通過懶加載就不會(huì)一次性把所有組件都加載進(jìn)來,而是當(dāng)你訪問到那個(gè)組件的時(shí)候才會(huì)加載那一個(gè)。對(duì)于組件比較多的應(yīng)用會(huì)提高首次加載速度。

五、<router-link>

在vue-router 1中,使用的是

在vue-router 2中,使用了<router-link></router-link>替換1版本中的a標(biāo)簽

<!-- 字符串 --><router-link to="home">Home</router-link><!-- 渲染結(jié)果 --><a href="home" rel="external nofollow" >Home</a><!-- 使用 v-bind 的 JS 表達(dá)式 --><router-link v-bind:to="'home'">Home</router-link><!-- 不寫 v-bind 也可以,就像綁定別的屬性一樣 --><router-link :to="'home'">Home</router-link><!-- 同上 --><router-link :to="{ path: 'home' }">Home</router-link><!-- 命名的路由 --><router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link><!-- 帶查詢參數(shù),下面的結(jié)果為 /register?plan=private --><router-link :to="{ path: 'register', query: { plan: 'private' }}">Register</router-link>
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 台安县| 昆明市| 凤城市| 称多县| 尚义县| 汾阳市| 祁阳县| 新余市| 门头沟区| 鹤庆县| 河南省| 鹤岗市| 新和县| 蕉岭县| 探索| 汤原县| 丽江市| 宁陵县| 美姑县| 张家口市| 老河口市| 湘潭市| 青岛市| 龙泉市| 静安区| 隆化县| 米脂县| 英德市| 舒城县| 乌海市| 清丰县| 柘城县| 甘泉县| 富川| 沂源县| 阜南县| 醴陵市| 咸宁市| 秭归县| 浦东新区| 沧州市|