前言
vue一個重要的方面就是路由,下面是自己寫的一個路由的例子分享給大家供大家參考學(xué)習(xí),下面來看看詳細(xì)的介紹。
方法如下:
1、引入依賴庫就不必再說
2、創(chuàng)建組件
兩種寫法
第一種:間接
<template id="home"> <div> <h1>Home</h1> <p>{{msg}}</p> </div> </template> var About = Vue.extend({ template: '#about' });第二種:直接
var Out = Vue.extend({ template: '<div><h1>Out</h1><p>This is the tutorial out vue-router.</p></div>' }); 3、創(chuàng)建 router 實例,傳 'routes'路由映射配置
var router = new VueRouter({ routes: [ { path: '/路徑', component: 組件名 }, { path: '/', component: 組件名}, //設(shè)置默認(rèn)路徑 { path: "*", component:Home }//路徑不存在 <br> ] }); 4、創(chuàng)建和掛載根實例。記得要通過 router 配置參數(shù)注入路由,從而讓整個應(yīng)用都有路由功能
var vm = new Vue({ router: router }).$mount('#app'); 整體的demo
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>hello world</title></head><body> <div id="app"> <div> <!-- 4、<router-link>默認(rèn)會被渲染成一個 `<a>` 標(biāo)簽 ,to指令跳轉(zhuǎn)到指定路徑 --> <router-link to="/home">Go to Home</router-link> <router-link to="/about">Go to About</router-link> <router-link to="/out">Go to Out</router-link> </div> <!-- 5、在頁面上使用<router-view></router-view>標(biāo)簽,用于渲染匹配的組件 --> <!--這里顯示的是展示的界面--> <router-view></router-view> </div> <template id="home"> <div> <h1>Home</h1> <p>{{msg}}</p> </div> </template> <template id="about"> <div> <h1>about</h1> <p>This is the tutorial about vue-router.</p> </div> </template> <!-- 0、引入依賴庫 --> <script src="../js/vue2.0.js" type="text/javascript" charset="utf-8"></script><script src="lib/vue-router.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> /* 1、創(chuàng)建組件 */ var Home = Vue.extend({ template: '#home', data: function() { return { msg: 'Hello, vue router!' } } }); var About = Vue.extend({ template: '#about' }); var Out = Vue.extend({ template: '<div><h1>Out</h1><p>This is the tutorial out vue-router.</p></div>' }); // 2. 創(chuàng)建 router 實例,然后傳 `routes`路由映射 配置 var router = new VueRouter({ routes: [ { path: '/home', component: Home }, { path: '/about', component: About }, { path: '/out', component: Out }, {path: '/', component: Home },//設(shè)置默認(rèn)路徑 { path: "*", component:Home }//路徑不存在 ] }); // 3. 創(chuàng)建和掛載根實例。記得要通過 router 配置參數(shù)注入路由,從而讓整個應(yīng)用都有路由功能 var vm = new Vue({ router: router }).$mount('#app'); // 現(xiàn)在,應(yīng)用已經(jīng)啟動了! </script></body></html>
新聞熱點
疑難解答
圖片精選