1. 程式人生 > >VUE起步構建簡單單頁應用

VUE起步構建簡單單頁應用

環境搭建工作:

1.先安裝node,git工具(便於命令列操作)

2.換源(npm淘寶映象網站:https://npm.taobao.org/)
  命令:npm install -g cnpm --registry=https://registry.npm.taobao.org
3.安裝VUE(命令:cnpm  install -g vue-cli)
4.安裝WebPack(命令:cnpm install webpack -g )

5.通過vue cli腳手架初始化一個自己的vue專案(命令:vue init webpack projectName)

6.cd projectName(執行cnpm install)
7.cnpm run dev(會自動開啟瀏覽器看到Hello介面)

8.VUE編寫完成的專案使用webpack打包(命令:cnpm run build),檔案生成在dist資料夾下面

打包完之後生成的檔案,使用預設的vue cli打包的是單頁的專案(只有一個入口檔案),隨便丟在伺服器下面都可以進行訪問(eg:nginx,apache,tomcat:localhost/index.html)


我們進行簡單的擴充套件一下這個專案,專案的目錄圖:


在components資料夾下面新增2個模組First.vue

<template>
  <div >
    
    <h1>first.vue</h1>
  </div>
</template>

Two.vue
<template>
  <div >
    
    <h1>two.vue</h1>
  </div>
</template>


定義路由檔案(在router資料夾下面):

router.js

import Vue from 'vue'
import Router from 'vue-router'
import Hello from 'components/Hello'
import First from 'components/First'
import Two from 'components/Two'
Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      component: Hello
    },
    {
      path: '/first',
      component: First
    },
    {
      path: '/two',
      component: Two
    }
  ]
})

App.vue
<template>
  <div id="app">
    <img src="./assets/logo.png">
       <div class="list-group">
 
        <router-link to="/">首頁</router-link> 
        <router-link to="/first">first</router-link>
        <router-link to="/two">two</router-link>

      </div>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'app'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

然後執行命令:cnpm run dev


注意瀏覽器裡面的路由http://localhost:8080/#/first,http://localhost:8080/#/two,只要你看到的網站路由類似這樣的基本上都是目前流行的前端JS框架寫出來的。

注:這種流行的前端框架寫程式碼必須在nodejs環境下面去寫,否則寫的程式碼無法壓縮,webpack無法起作用,因為webpack依賴與npm,作為一位合格的前端開發者nodejs必須會吧,不會的話趕緊去學吧。