初識vue 2.0(2):路由與組件
1,在上一篇的創建工程中,使用的的模版 webpack-simple 只是創建了一個簡單的demo,並沒有組件和路由功能,此次采用了webpack模版,自動生成組件和路由。^_^
在模版初始化時,因為ESLint語法檢查過於嚴格,可以暫時不要開啟。
vue init webpack myapp ? Install vue-router? Yes ? Use ESLint to lint your code? No ? Setup unit tests with Karma + Mocha? Yes ? Setup e2e tests with Nightwatch? Yes cd myapp npm install npm run dev
2,安裝完成後,你會發現 src 目錄中多了 components 和 router 。
此時,App.vue 依然是 template、script、style三部分組成,但是在template中,你會發現多了一個router-view標簽。
<template> <div id="app"> <h1>{{ msg }}</h1> <router-view></router-view> </div> </template> <script> export default { name: ‘app‘, data () { return { msg: ‘我是一個banner‘ } } } </script>
3,router目錄中,自動生成了默認的index.js路由文件,其中默認的訪問指向了Hello組件,我們來增加一個Game組件。
在了解不深入的時候,模仿就好了。^_^
import Vue from ‘vue‘ import Router from ‘vue-router‘ import Hello from ‘@/components/Hello‘ import Game from ‘@/components/Game‘//新增Game組件 Vue.use(Router) export default new Router({ routes: [ { path: ‘/‘, name: ‘Hello‘, component: Hello }, { path: ‘/game‘,//新增game路由 name: ‘Game‘, component: Game } ] })
4,在components目錄中,原有個Hello.vue組件文件,我們簡單改寫一下,再新增個Game.vue 組件。(樣式已被移到html中)
a) Hello.vue
<template> <div class="hello"> <h2>{{ msg }}</h2> <ul> <li><a href="#/game">我是一個鏈接</a></li> </ul> </div> </template> <script> export default { name: ‘hello‘, data () { return { msg: ‘我是hello模塊‘ } } } </script>
b) Game.vue
<template> <div class="game"> <h2>{{ msg }}</h2> <ul> <li><a href="#/">返回</a></li> </ul> </div> </template> <script> export default { name: ‘game‘, data () { return { msg: ‘我是game模塊‘ } } } </script>
5,main.js 文件無需改寫,但我們可以看一下內容,主要是啟用了路由模塊。 ^_^
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from ‘vue‘ import App from ‘./App‘ import router from ‘./router‘ Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: ‘#app‘, router, template: ‘<App/>‘, components: { App } })
6,在調試通過後,可以使用 vue run build 構建發布包。默認生成的文件(html、css、js)路徑在dist,可以通過修改config目錄中index.js 來決定發布代碼的結構與路徑。
訪問效果,默認首頁:http://localhost/myapp/dist/#/
點擊超鏈接,跳轉到game模塊:http://localhost/myapp/dist/#/game
7,至此,一個簡單的通過路由來實現組件化的前端應用demo就完成了。
因為這是一個單頁應用,url是使用錨點的方式來進行頁面切換的。
關於vue的配置信息,會在後續的章節中介紹,下一篇會先介紹vue中ajax的使用。
初識vue 2.0(2):路由與組件