直接引用vue.js使用路由的方法:首先引入【vue.JS】和【vue-router.JS】;然后創(chuàng)建掛載的dom元素,并創(chuàng)建路由組件;接著定義路由,并創(chuàng)建router實(shí)例;最后創(chuàng)建vue實(shí)例并掛載。
本教程操作環(huán)境:windows7系統(tǒng)、Vue2.9.6版,該方法適用于所有品牌電腦。
【相關(guān)文章推薦:vue.js】
直接引用vue.js使用路由的方法:
直接引入 vue.js 的方式使用路由很簡(jiǎn)單, 只需要再直接引入一個(gè) vue-router.JS
即可.
具體的實(shí)現(xiàn)步驟:
1, 引入 vue.JS 和 vue-router.JS
<script src="https://unpkg.com/vue/dist/vue.js"> </script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"> </script>
2, 創(chuàng)建掛載的 dom 元素
<div id="app"></App>
3, 創(chuàng)建路由組件
const com1 = { template: '<div > 路由 1</div>' } const com2 = { template: '<div > 路由 2</div>' }
4, 定義路由
const routes = [ { path: '/hash1', component: com1 }, { path: '/hash2', component: com2 } ]
5, 創(chuàng)建 router 實(shí)例
const router = new VueRouter({ routes })
6, 創(chuàng)建 vue 實(shí)例并掛載
const App = new Vue({ router }).$mount('#app');
下面是具體的代碼:
<!DOCTYPE HTML> <HTML> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title> Document </title> <script src="https://unpkg.com/vue/dist/vue.js"> </script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"> </script> </head> <body> <div id="app"> <h1> Hello ! </h1> <p> <!-- 使用 router-link 組件來導(dǎo)航. --> <!-- 通過傳入 `to` 屬性指定鏈接. --> <!-- <router-link> 默認(rèn)會(huì)被渲染成一個(gè) `<a>` 標(biāo)簽 --> <router-link to="/hash1"> 切換至 com1 </router-link> <router-link to="/hash2"> 切換至 com2 </router-link> </p> <!-- 路由出口 --> <!-- 路由匹配到的組件將渲染在這里 --> <router-view> </router-view> <!-- router-link 上的其他屬性: --> <!-- 設(shè)置 replace 屬性的話, 當(dāng)點(diǎn)擊時(shí), 會(huì)調(diào)用 router.replace() 而不是 router.push(), 導(dǎo)航后不會(huì)留下 history 記錄. --> <!-- <router-link :to="{ path:'/abc'}" replace></router-link> --> <!-- 有時(shí)候想要 <router-link> 渲染成某種標(biāo)簽, 例如 <li>. 于是我們使用 tag prop 類指定何種標(biāo)簽, 同樣它還是會(huì)監(jiān)聽點(diǎn)擊, 觸發(fā)導(dǎo)航. --> <!-- <router-link to="/foo" tag="li">foo</router-link> --> <!-- active-class 設(shè)置 鏈接激活時(shí)使用的 CSS --> <!-- event 聲明可以用來觸發(fā)導(dǎo)航的事件. 可以是一個(gè)字符串或是一個(gè)包含字符串的數(shù)組. --> </div> </body> <script> // 1. 定義 (路由) 組件. const com1 = { template: '<div > 路由 1</div>' } const com2 = { template: '<div > 路由 2</div>' } // 2. 定義路由 // 每個(gè)路由應(yīng)該映射一個(gè)組件. 其中 "component" 可以是 通過 Vue.extend() // 創(chuàng)建的組件構(gòu)造器, 或者, 只是一個(gè)組件配置對(duì)象. const routes = [{ path: '/hash1', component: com1 }, { path: '/hash2', component: com2 }] // 3. 創(chuàng)建 router 實(shí)例, 然后傳 `routes` 配置 const router = new VueRouter({ routes // (縮寫)相當(dāng)于 routes: routes }) // 4. 創(chuàng)建和掛載根實(shí)例. // 要通過 router 配置參數(shù)注入路由, 從而讓整個(gè)應(yīng)用都有路由功能 const App = new Vue({ router }).$mount('#app'); //el 是自動(dòng)掛載, mount 是手動(dòng)掛載(延時(shí)) </script> </HTML>
相關(guān)學(xué)習(xí)推薦:js視頻教程