vue一個重要的方面就是路由,下面是自己寫的一個路由的例子:
1、引入依賴庫就不必再說
2、創建組件
兩種寫法
第一種:間接 <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、創建 router 實例,傳 'routes'路由映射配置
var router = new VueRouter({ routes: [ { path: '/路徑', component: 組件名 }, { path: '/', component: 組件名}, //設置默認路徑 { path: "*", component:Home }//路徑不存在
] });
4、創建和掛載根實例。記得要通過 router 配置參數注入路由,從而讓整個應用都有路由功能
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>默認會被渲染成一個 `<a>` 標簽 ,to指令跳轉到指定路徑 --> <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>標簽,用於渲染匹配的組件 --> <!--這里顯示的是展示的界面--> <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、創建組件 */ 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. 創建 router 實例,然后傳 `routes`路由映射 配置 var router = new VueRouter({ routes: [ { path: '/home', component: Home }, { path: '/about', component: About }, { path: '/out', component: Out }, {path: '/', component: Home },//設置默認路徑 { path: "*", component:Home }//路徑不存在 ] }); // 3. 創建和掛載根實例。記得要通過 router 配置參數注入路由,從而讓整個應用都有路由功能 var vm = new Vue({ router: router }).$mount('#app'); // 現在,應用已經啟動了! </script> </body> </html>
關於路由嵌套
在配置routes映射時添加children配置
如下:
var router = new VueRouter({ routes:[ {path:'/home',component:Home, children:[//子路由 {path:'news',component:News}, {path:'change',component:change} ]}, {path:'/me',component:Me}, {path:'/',component:Me} ] })
關於具體的demo可以參考GitHub上,另外還總結了一些自己最近在學習的阿里雲上傳圖片等,會逐步更新,敬請指教!
轉載請注明出處,謝謝合作