一:准備工作
安裝nodejs + 安裝webpack + 配置環境變量 => 確保在dos界面的任何路徑都都可直接使用命令
二:搭建項目
1.全局安裝vue腳手架 [DOS界面]
npm install vue-cli -g
2.新建項目並啟動服務 [進入項目所在目錄]
vue init webpack firstDemo 或 vue init webpack-simple firstDemo => 前者構建的應用豐富於后一個
npm install => 生成node_modules
npm run dev => 啟動服務(webpack內部搭建了一個服務器)
此時整個目錄的結構大概是:
3.編輯main.js [入口文件]
//main.js import Vue from 'vue' import VueRouter from 'vue-router' import App from './APP.vue' import index from './components/index.vue' import hello from './components/hello.vue' Vue.use(VueRouter); const routes=[ //定義路由 {path:'/' ,redirect:'/index'}, {path:'/index' ,component:index} {path:'/hello',component:hello} ] const router=new VueRouter({routes}); //創建VueRouter實例 const app=new Vue({ //創建和掛載實例 router, render:h=>h(App) }).$mount('#app') //與App.vue中根級元素的id一致
4.編輯App.vue文件
//App.vue <template> <div id='app'> <img src='./assets/logo.png'> <router-link to='/index'>首頁</router-link> <router-link to='/hello'>hello頁</router-link> <router-view></router-view> //路由匹配到的組件會渲染到這里 </div> </template>
5.編輯hello.vue [index.vue與之類似]
//hello.vue <template> <p>我是hello頁</p> </template>
6.查看效果 [hello頁面]
以下是vue-cli1.0和vue-cli2.0版本的寫法區別
一:
1.0是通過router的map方法映射路由,並且map接收的是一個對象
2.0版本中map ()被替換了,通過實例化VueRouter並定義一個數組來映射路由。
二:
1.0通過router.start()來初始化路由
2.0中被替換成直接掛在到vue根實例上進行初始化。
三:
1.0中通過v-link來制定導航鏈接
2.0中可以直接使用router-link來導航