目錄結(jié)構(gòu)
App.vue文件
<template>
<div id="app">
<div id="nav">
<router-link :to="{name:'home'}">Home</router-link> |
<router-link to="/about">About</router-link> |
<router-link :to="{name:'news',params:{id:111} }">news</router-link> |
<router-link to="/demos/demo123">demos</router-link>
</div>
<hr>
<span @click="jumpHome">首頁</span>
<span @click="jumpAbout">其他</span>
<router-view/>
</div>
</template>
<script>
export default {
name:'App',
methods:{
jumpHome(){
console.log(this);
this.$router.push('/')
},
jumpAbout(){
console.log(this);
this.$router.push('/about')
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
#nav {
padding: 30px;
}
#nav a {
font-weight: bold;
color: #2c3e50;
}
#nav a.exact-active {
color: #42b983;
}
span{
color: #42b983;
cursor: pointer;
}
</style>
一 . router-link 其實(shí)就是對 跳轉(zhuǎn)鏈接的封裝 默認(rèn)的標(biāo)簽是 a標(biāo)簽
屬性:
1.to 跳轉(zhuǎn)鏈接
2.tag 可以改其他標(biāo)簽 如(span等):
router-link tag='span' to="/home">home</router-link>
默認(rèn)類名:
1.router-link-exact-active
當(dāng)對應(yīng)的路由匹配成功時(shí), 會(huì)自動(dòng)給當(dāng)前 router-link 加上該類名
在url路徑后有 /
2.router-link-exact-active
只是在精準(zhǔn)匹配下才會(huì)出現(xiàn)的 (/home)
router-link-exact-active
router-link-active
二 . <router-view/> 顯示窗口
簡單理解 一個(gè)標(biāo)簽就是一個(gè)窗口 (頁面)
main.js文件
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
}
]
})
懶加載
當(dāng)打包構(gòu)建應(yīng)用時(shí)氏仗,Javascript 包會(huì)變得非常大嫌术,影響頁面加載。
如果我們能把不同路由對應(yīng)的組件分割成不同的代碼塊菜枷,然后當(dāng)路由被訪問的時(shí)候才加載對應(yīng)組件,這樣就更加高效了
主要代碼塊 ↓
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ './views/About.vue')
這一注釋就是在點(diǎn)擊 about的時(shí)候可以網(wǎng)頁加載時(shí)的名
/* webpackChunkName: "about" */
引入的組件路徑
'./views/About.vue'
懶加載的方式(推薦方式三)
方式一: 結(jié)合Vue的異步組件和Webpack的代碼分析.
const Home = resolve => { require.ensure(['../components/Home.vue'],
() => { resolve(require('../components/Home.vue')) }
)};
方式二: AMD寫法
const About = resolve => require(['../components/About.vue'], resolve);
方式三: 在ES6中, 我們可以有更加簡單的寫法來組織Vue異步組件和Webpack的代碼分割.
const Home = () => import('../components/Home.vue')