
本文作者 Jinkey(微信公眾號 jinkey-love,官網 https://jinkey.ai)
原文鏈接 https://jinkey.ai/post/tech/vue2.0-xin-shou-wan-quan-tian-keng-gong-lue-cong-huan-jing-da-jian-dao-fa-bu
文章允許非篡改署名轉載,刪除或修改本段版權信息轉載的,視為侵犯知識產權,我們保留追求您法律責任的權利,特此聲明!
感謝 showonne、yubang 技術指導
Demo 地址:
http://demo.jinkey.io/vue2
源碼:
https://github.com/Jinkeycode/vue2-example
什么是 Vue
Vue 是一個前端框架,特點是
數據綁定
比如你改變一個輸入框 Input 標簽的值,會自動同步更新到頁面上其他綁定該輸入框的組件的值

![]()
數據綁定
組件化
頁面上小到一個按鈕都可以是一個單獨的文件.vue,這些小組件直接可以像樂高積木一樣通過互相引用而組裝起來


Vue2.0 推薦開發環境


Homebrew 1.0.6(Mac)、Node.js 6.7.0、npm 3.10.3、webpack 1.13.2、vue-cli 2.4.0、Atom 1.10.2
安裝環境
打開終端運行以下命令
安裝brew
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
安裝 nodejs
brew install nodejs
用 npm install npm@3.10.3 更新 npm 版本報錯:
(node:42) fs: re-evaluating native module sources is not supported.
解決辦法:
在官網下載6.70的安裝包再安裝一次(剛剛相當於幫你配置好環境變量,現在再安裝一次升級到最新的 npm)
- 好像以前官網的安裝包不會自動配置環境變量的,由於我電腦上之前安裝過 nodejs 所以環境變量已經配置好了,不知道現在的安裝包會不會自動配置環境變量。
Windows 下直接下載安裝包即可
獲取nodejs模塊安裝目錄訪問權限
sudo chmod -R 777 /usr/local/lib/node_modules/
安裝淘寶鏡像
npm install -g cnpm --registry=https://registry.npm.taobao.org
安裝webpack
cnpm install webpack -g
安裝vue腳手架
npm install vue-cli -g
在硬盤上找一個文件夾放工程用的,在終端中進入該目錄
Mac
cd 目錄路徑
根據模板創建項目
vue init webpack-simple 工程名字<工程名字不能用中文>
或者創建 vue1.0 的項目
vue init webpack-simple#1.0 工程名字<工程名字不能用中文>
會有一些初始化的設置,如下輸入:
Target directory exists. Continue? (Y/n)
直接回車默認(然后會下載 vue2.0模板,這里可能需要連代理)
Project name (vue-test)
直接回車默認
Project description (A Vue.js project)
直接回車默認
Author
寫你自己的名字
cd 命令進入創建的工程目錄
工程目錄如圖所示:

安裝項目依賴
一定要從官方倉庫安裝,npm 服務器在國外所以這一步安裝速度會很慢。
npm install
不要從國內鏡像cnpm安裝(會導致后面缺了很多依賴庫)
cnpm install
安裝 vue 路由模塊vue-router
和網絡請求模塊vue-resource
cnpm install vue-router vue-resource --save
啟動項目
npm run dev
填坑(以下坑可能由於 vue2.0 導致其他相關編譯打包工具沒更新導致的)
【重點】后來發現這些坑是由於 npm 不是最新的版本3.10.2, 用 npm 3.9.5就會出現以下坑
解決辦法: 請運行以下命令
npm update -g
報錯
Error: Cannot find module 'opn'
Error: Cannot find module 'webpack-dev-middleware'
Error: Cannot find module 'express'
Error: Cannot find module 'compression'
Error: Cannot find module 'sockjs'
Error: Cannot find module 'spdy'
Error: Cannot find module 'http-proxy-middleware'
Error: Cannot find module 'serve-index'
如果你用的是老版本的 vue-cli 還可能報其他錯誤,需要更新一下 vue-cli
npm update vue-cli
然后可以查看一下當前全局 vue-cli 的版本
npm view vue-cli
安裝一下這個依賴到工程開發環境
cnpm install opn --save-dev
cnpm install webpack-dev-middleware --save-dev
cnpm install express --save-dev
cnpm install compression --save-dev
cnpm install sockjs --save-dev
cnpm install spdy --save-dev
cnpm install http-proxy-middleware --save-dev
cnpm install serve-index --save-dev
cnpm install connect-history-api-fallback --save-dev
再啟動項目,報錯
ERROR in ./src/main.js
Module build failed: Error: Cannot find module 'babel-runtime/helpers/typeof'
at Function.Module._resolveFilename (module.js:440:15)
at Function.Module._load (module.js:388:25)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Volumes/MacStorage/Coding/Web/vue-test/node_modules/.6.17.0@babel-core/lib/transformation/file/index.js:6:16)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
@ multi main
ERROR in ./~/.2.1.0-beta.8@webpack-dev-server/client/socket.js
Module not found: Error: Can't resolve 'sockjs-client' in '/Volumes/MacStorage/Coding/Web/vue-test/node_modules/.2.1.0-beta.8@webpack-dev-server/client'
@ ./~/.2.1.0-beta.8@webpack-dev-server/client/socket.js 1:13-37
@ ./~/.2.1.0-beta.8@webpack-dev-server/client?http://localhost:8080
@ multi main
安裝一下 babel-runtime
cnpm install babel-helpers --save-dev
啟動項目,再次報錯
Module build failed: Error: Cannot find module 'babel-helpers'
Module build failed: Error: Cannot find module 'babel-traverse'
Module build failed: Error: Cannot find module 'json5'
Module build failed: Error: Cannot find module 'babel-generator'
Module build failed: Error: Cannot find module 'detect-indent'
Module build failed: Error: Cannot find module 'jsesc'
找不到依賴那就再安裝一下
cnpm install babel-helpers --save-dev
cnpm install babel-traverse --save-dev
cnpm install json5 --save-dev
...不寫了,請把全部把舊的環境全部清除,更新到最新版本
解決辦法概述
遇到
Module build failed: Error: Cannot find module '模塊名'
那就安裝
cnpm install 模塊名 --save-dev(關於環境的,表現為npm run dev 啟動不了)
cnpm install 模塊名 --save(關於項目的,比如main.js,表現為npm run dev 成功之后控制台報錯)
比如escape-string-regexp、strip-ansi、has-ansi、is-finite、emojis-list
終於可以啟動項目了
輸入完命令會自動啟動瀏覽器,如果默認打開 IE 不行
npm run dev
自動啟動瀏覽器就會看到這 帥帥的界面了。

開始 Vue 之旅
打開 IDE
推薦 Atom 打開項目,需要安裝 Vue 語法高亮的插件

使用官網文檔學習基礎
我們來看官網的一個例子,(中文文檔請自行上網搜索)


打開 工程目錄下的 App.vue
template 寫 html,script寫 js,style寫樣式

為了方便敘述,我們把官網例子寫在同一個組件內
這里有兩個坑:
第一。一個組件下只能有一個並列的 div,可以這么寫,所以復制官網示例的時候只要復制 div 里面的內容就好。

但是不能這樣寫:


第二。數據要寫在 return 里面而不是像文檔那樣子寫

錯誤的寫法:

這樣子可以自己啃完官網文檔組件之前的部分了。

來玩玩組件
前面講得基本上都是各種常用組件的數據綁定,下面還得說說的是 Vue 的組件的使用。
在工程目錄/src
下創建component
文件夾,並在component
文件夾下創建一個 firstcomponent.vue
並寫仿照 App.vue 的格式和前面學到的知識寫一個組件。
<template> <div id="firstcomponent"> <h1>I am a title.</h1> <a> written by {{ author }} </a> </div> </template> <script type="text/javascript"> export default { data () { return { author: "微信公眾號 jinkey-love" } } } </script> <style> </style>
duang... 不能按官網文檔那樣子叫我做就做,我得先試試再告訴你,我做完效果是這樣子的,希望觀眾做完也是這樣子。(迷之微笑 )

然后在 App.vue 使用組件 ( 因為在 index.html
里面定義了<div id="app"></div>所以就以這個組件作為主入口,方便 )
第一步,引入。在<script></script>
標簽內的第一行寫
import firstcomponent from './component/firstcomponent.vue'
第二步,注冊。在<script></script>
標簽內的 data 代碼塊后面加上 components: { firstcomponent }。記得中間加英文逗號!!!
export default { data () { return { msg: 'Hello Vue!' } }, components: { firstcomponent } }
第三步,使用。
在<template></template>
內加上<firstcomponent></firstcomponent>
<template>
<div id="app">

<h1>{{ msg }}</h1>
<firstcomponent></firstcomponent>
</div>
</template>
完成后的代碼:

這時候看看瀏覽器上的 http://localhost:8080/
頁面(之前打開過就會自動刷新),如果你沒看到效果是因為你沒有對 App.vue
和 firstcomponent.vue
進行保存操作,保存后頁面會自動刷新。

使用路由搭建單頁應用
之前已經通過命令安裝了vue-router
cnpm install vue-router --save
在webpack.config.js
加入別名
resolve: {
alias: {vue: 'vue/dist/vue.js'} }
為什么要加 alias 配置項?其作用可以在文檔中有相應的描述:

修改完之后的webpack.config.js
是這樣子的:
var path = require('path') var webpack = require('webpack') module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'build.js' }, resolveLoader: { root: path.join(__dirname, 'node_modules'), }, module: { loaders: [ { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.vue$/, loader: 'vue' }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.js$/, loader: 'babel', exclude: /node_modules/ }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.(png|jpg|gif|svg)$/, loader: 'file', query: { name: '[name].[ext]?[hash]' } } ] }, resolve: { alias: {vue: 'vue/dist/vue.js'} }, devServer: { historyApiFallback: true, noInfo: true }, devtool: '#eval-source-map' } if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ]) }
再按之前的方法寫一個組件 secondcomponent.vue
<template> <div id="secondcomponent"> <h1>I am another page</h1> <a> written by {{ author }} </a> <p> 感謝 <a href="https://github.com/showonne">showonne</a>大神的技術指導</p> </div> </template> <script> export default { data() { return { author: "微信公眾號 jinkey-love", articles: [], } } } } </script> <style> </style>
這時候修改 main.js,引入並注冊 vue-router
import VueRouter from "vue-router"; Vue.use(VueRouter);
並且配置路由規則和 app 啟動配置項加上 router,舊版的 router.map 方法在 vue-router 2.0
已經不能用了。修改后的main.js
如下:
import Vue from 'vue' import App from './App.vue' import VueRouter from "vue-router"; import VueResource from 'vue-resource' //開啟debug模式 Vue.config.debug = true; Vue.use(VueRouter); Vue.use(VueResource); // 定義組件, 也可以像教程之前教的方法從別的文件引入 const First = { template: '<div><h2>我是第 1 個子頁面</h2></div>' } import secondcomponent from './component/secondcomponent.vue' // 創建一個路由器實例 // 並且配置路由規則 const router = new VueRouter({ mode: 'history', base: __dirname, routes: [ { path: '/first', component: First }, { path: '/second', component: secondcomponent } ] }) // 現在我們可以啟動應用了! // 路由器會創建一個 App 實例,並且掛載到選擇符 #app 匹配的元素上。 const app = new Vue({ router: router, render: h => h(App) }).$mount('#app')
這樣子改完再打開瀏覽器看看。

點擊那兩個鏈接試試,會發現<router-view class="view"></router-view>
的內容已經展示出來,同時注意瀏覽器地址已經變更。

另外,也可以把 App.vue 的內容寫在 main.js 也是可以的不過不建議這么做

如果你使用 vue1.0和0.7版本的 vue-router,請參照下面這個教程, 他整個系列都不錯的,當然僅限於 vue1.0 :
給頁面加點動態數據
這時候的頁面都是靜態的(數據在寫程序的時候已經固定了不能修改),而每個應用基本上都會請求外部數據以動態改變頁面內容。對應有一個庫叫 vue-resource
幫我們解決這個問題。
使用命令行安裝
cnpm install vue-resource --save
在 main.js 引入並注冊 vue-resource
:
import VueResource from 'vue-resource' Vue.use(VueResource);
我們在 secondcomponent.vue 上來動態加載數據
添加一個列表:
<ul>
<li v-for="article in articles">
{{article.title}}
</li>
</ul>
在 data 里面加入數組 articles 並賦值為[]
然后在 data 后面加入加入鈎子函數 mounted
(詳細請參照官方文檔關於 vue 生命周期的解析),data 和 mount 中間記得記得加逗號
mounted: function() { this.$http.jsonp('https://api.douban.com/v2/movie/top250?count=10', {}, { headers: { }, emulateJSON: true }).then(function(response) { // 這里是處理正確的回調 this.articles = response.data.subjects // this.articles = response.data["subjects"] 也可以 }, function(response) { // 這里是處理錯誤的回調 console.log(response) }); }
這里使用的是豆瓣的公開 GET 接口,如果接口是跨域的 POST 請求,則需要在服務器端配置:
Access-Control-Allow-Origin: *
這時候運行看看。等一會接口返回數據,咦,數據加載出來了,棒棒噠 !

更多 vue-router
的使用方法可以看
vue-router 0.7
http://m.doc00.com/doc/1001004eg
vue-router 2.0
http://router.vuejs.org/zh-cn/index.html
來拯救如此難看的界面
組件、雙向綁定、路由、數據請求等基本特性都能用了,寫到這里一個單頁應用基本上成型了。但是,這幾面也太 TM 難看了吧。自己寫 UI 框架太費勁?那就上網找一個吧。
本來想給大家介紹 Vux 的,因為他用的是微信的 WeUI 設計規范,對於開發微信小程序或者微信內的網頁非常和諧,但由於寫這篇文章的時候 Vux 還不支持 vue2.0,只能用別的框架了。
命令行安裝 ElementUI (此處某公司的人應該發紅包了...)
cnpm install element-ui@next -S
然后在 main.js 引入並注冊
import Element from 'element-ui' import 'element-ui/lib/theme-default/index.css' Vue.use(Element)
保存,這時候程序報錯
Uncaught Error: Module parse failed: /Users/**/Desktop/vue2/node_modules/.1.0.0-rc.5@element-ui/lib/theme-default/index.css Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type.
官網文檔又有坑了,安裝教程也不跟我們說這一步,當我們都是高手了...
報錯是由於我們引入了index.css
這個 CSS 文件,但是 webpack 打包的時候無法識別並轉換成 js,所以就需要配置才能讀取 css 和字體文件,運行命令安裝下面三個東西(如果之前安裝過就不需要了)
cnpm install style-loader --save-dev
cnpm install css-loader --save-dev
cnpm install file-loader --save-dev
在 webpack.config.js
中的 loaders 數組加入以下配置,記得該加逗號的地方加逗號!
{
test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.css$/, loader: "style!css" }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.(eot|woff|woff2|ttf)([\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\?]?.*)$/, loader: "file" }
修改完的 webpack.config.js
如下
var path = require('path') var webpack = require('webpack') module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'build.js' }, resolveLoader: { root: path.join(__dirname, 'node_modules'), }, module: { loaders: [ { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.vue$/, loader: 'vue' }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.js$/, loader: 'babel', exclude: /node_modules/ }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.css$/, loader: "style!css" }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.(eot|woff|woff2|ttf)([\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\?]?.*)$/, loader: "file" }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.(png|jpg|gif|svg)$/, loader: 'file', query: { name: '[name].[ext]?[hash]' } } ] }, resolve: { alias: {vue: 'vue/dist/vue.js'} }, devServer: { historyApiFallback: true, noInfo: true }, devtool: '#eval-source-map' } if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ]) }
給豆瓣的電影列表套個衣服(樣式) :
<el-card class="box-card">
<div slot="header" class="clearfix">
<h1 style="line-height: 36px; color: #20A0FF">豆瓣電影排行榜</h2>
</div>
<div v-for="article in articles" class="text item">
{{article.title}}
</div>
</el-card>
打開瀏覽器,輸入網址:


列表比之前漂亮多了,你還可以參照 ElementUI 的文檔使用更多組件樣式
編譯
npm run build
又報錯了...orz
ERROR in build.js from UglifyJs
SyntaxError: Unexpected token punc «(», expected punc «:» [build.js:32001,6]
解決辦法(21061019 showonne 提交 PR 已合並到主分支)
cnpm install babel-preset-es2015 --save-dev
cnpm install babel-preset-stage-0 --save-dev
然后在項目目錄下創建一個.babelrc
文件,內容如下:
{
presets: ['es2015', 'stage-0'] }
或者在webpack.config.js
中這里
{
test: /\\\\.js$/, loader: 'babel', exclude: /node_modules/ }
加入 presets 配置,修改成下面醬紫:
{
test: /\\\\.js$/, loader: 'babel', exclude: /node_modules/, query: {presets: ['es2015', 'stage-0'] }
再次執行 npm run build
就可以了,后來發現直接運行 webpack 命令也是可以打包的
webpack --color --progress
接着把 index.html 和整個 dist 目錄丟到服務器就可以了。
如果你覺得這篇文章寫得好,不需要打賞,你可以下載我朋友做的一個閱讀工具,可以訂閱公眾號和簡書、也可以看大神分享的優秀文章。
下載地址:[

Jinkey原創
感謝 showonne、yubang 技術指導
Demo 地址:
http://demo.jinkey.io/vue2
源碼:
https://github.com/Jinkeycode/vue2-example
什么是 Vue
Vue 是一個前端框架,特點是
數據綁定
比如你改變一個輸入框 Input 標簽的值,會自動同步更新到頁面上其他綁定該輸入框的組件的值

![]()
數據綁定
組件化
頁面上小到一個按鈕都可以是一個單獨的文件.vue,這些小組件直接可以像樂高積木一樣通過互相引用而組裝起來


Vue2.0 推薦開發環境


Homebrew 1.0.6(Mac)、Node.js 6.7.0、npm 3.10.3、webpack 1.13.2、vue-cli 2.4.0、Atom 1.10.2
安裝環境
打開終端運行以下命令
安裝brew
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
安裝 nodejs
brew install nodejs
用 npm install npm@3.10.3 更新 npm 版本報錯:
(node:42) fs: re-evaluating native module sources is not supported.
解決辦法:
在官網下載6.70的安裝包再安裝一次(剛剛相當於幫你配置好環境變量,現在再安裝一次升級到最新的 npm)
- 好像以前官網的安裝包不會自動配置環境變量的,由於我電腦上之前安裝過 nodejs 所以環境變量已經配置好了,不知道現在的安裝包會不會自動配置環境變量。
Windows 下直接下載安裝包即可
獲取nodejs模塊安裝目錄訪問權限
sudo chmod -R 777 /usr/local/lib/node_modules/
安裝淘寶鏡像
npm install -g cnpm --registry=https://registry.npm.taobao.org
安裝webpack
cnpm install webpack -g
安裝vue腳手架
npm install vue-cli -g
在硬盤上找一個文件夾放工程用的,在終端中進入該目錄
Mac
cd 目錄路徑
根據模板創建項目
vue init webpack-simple 工程名字<工程名字不能用中文>
或者創建 vue1.0 的項目
vue init webpack-simple#1.0 工程名字<工程名字不能用中文>
會有一些初始化的設置,如下輸入:
Target directory exists. Continue? (Y/n)
直接回車默認(然后會下載 vue2.0模板,這里可能需要連代理)
Project name (vue-test)
直接回車默認
Project description (A Vue.js project)
直接回車默認
Author
寫你自己的名字
cd 命令進入創建的工程目錄
工程目錄如圖所示:

安裝項目依賴
一定要從官方倉庫安裝,npm 服務器在國外所以這一步安裝速度會很慢。
npm install
不要從國內鏡像cnpm安裝(會導致后面缺了很多依賴庫)
cnpm install
安裝 vue 路由模塊vue-router
和網絡請求模塊vue-resource
cnpm install vue-router vue-resource --save
啟動項目
npm run dev
填坑(以下坑可能由於 vue2.0 導致其他相關編譯打包工具沒更新導致的)
【重點】后來發現這些坑是由於 npm 不是最新的版本3.10.2, 用 npm 3.9.5就會出現以下坑
解決辦法: 請運行以下命令
npm update -g
報錯
Error: Cannot find module 'opn'
Error: Cannot find module 'webpack-dev-middleware'
Error: Cannot find module 'express'
Error: Cannot find module 'compression'
Error: Cannot find module 'sockjs'
Error: Cannot find module 'spdy'
Error: Cannot find module 'http-proxy-middleware'
Error: Cannot find module 'serve-index'
如果你用的是老版本的 vue-cli 還可能報其他錯誤,需要更新一下 vue-cli
npm update vue-cli
然后可以查看一下當前全局 vue-cli 的版本
npm view vue-cli
安裝一下這個依賴到工程開發環境
cnpm install opn --save-dev
cnpm install webpack-dev-middleware --save-dev
cnpm install express --save-dev
cnpm install compression --save-dev
cnpm install sockjs --save-dev
cnpm install spdy --save-dev
cnpm install http-proxy-middleware --save-dev
cnpm install serve-index --save-dev
cnpm install connect-history-api-fallback --save-dev
再啟動項目,報錯
ERROR in ./src/main.js
Module build failed: Error: Cannot find module 'babel-runtime/helpers/typeof'
at Function.Module._resolveFilename (module.js:440:15)
at Function.Module._load (module.js:388:25)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Volumes/MacStorage/Coding/Web/vue-test/node_modules/.6.17.0@babel-core/lib/transformation/file/index.js:6:16)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
@ multi main
ERROR in ./~/.2.1.0-beta.8@webpack-dev-server/client/socket.js
Module not found: Error: Can't resolve 'sockjs-client' in '/Volumes/MacStorage/Coding/Web/vue-test/node_modules/.2.1.0-beta.8@webpack-dev-server/client'
@ ./~/.2.1.0-beta.8@webpack-dev-server/client/socket.js 1:13-37
@ ./~/.2.1.0-beta.8@webpack-dev-server/client?http://localhost:8080
@ multi main
安裝一下 babel-runtime
cnpm install babel-helpers --save-dev
啟動項目,再次報錯
Module build failed: Error: Cannot find module 'babel-helpers'
Module build failed: Error: Cannot find module 'babel-traverse'
Module build failed: Error: Cannot find module 'json5'
Module build failed: Error: Cannot find module 'babel-generator'
Module build failed: Error: Cannot find module 'detect-indent'
Module build failed: Error: Cannot find module 'jsesc'
找不到依賴那就再安裝一下
cnpm install babel-helpers --save-dev
cnpm install babel-traverse --save-dev
cnpm install json5 --save-dev
...不寫了,請把全部把舊的環境全部清除,更新到最新版本
解決辦法概述
遇到
Module build failed: Error: Cannot find module '模塊名'
那就安裝
cnpm install 模塊名 --save-dev(關於環境的,表現為npm run dev 啟動不了)
cnpm install 模塊名 --save(關於項目的,比如main.js,表現為npm run dev 成功之后控制台報錯)
比如escape-string-regexp、strip-ansi、has-ansi、is-finite、emojis-list
終於可以啟動項目了
輸入完命令會自動啟動瀏覽器,如果默認打開 IE 不行
npm run dev
自動啟動瀏覽器就會看到這 帥帥的界面了。

開始 Vue 之旅
打開 IDE
推薦 Atom 打開項目,需要安裝 Vue 語法高亮的插件

使用官網文檔學習基礎
我們來看官網的一個例子,(中文文檔請自行上網搜索)


打開 工程目錄下的 App.vue
template 寫 html,script寫 js,style寫樣式

為了方便敘述,我們把官網例子寫在同一個組件內
這里有兩個坑:
第一。一個組件下只能有一個並列的 div,可以這么寫,所以復制官網示例的時候只要復制 div 里面的內容就好。

但是不能這樣寫:


第二。數據要寫在 return 里面而不是像文檔那樣子寫

錯誤的寫法:

這樣子可以自己啃完官網文檔組件之前的部分了。

來玩玩組件
前面講得基本上都是各種常用組件的數據綁定,下面還得說說的是 Vue 的組件的使用。
在工程目錄/src
下創建component
文件夾,並在component
文件夾下創建一個 firstcomponent.vue
並寫仿照 App.vue 的格式和前面學到的知識寫一個組件。
<template> <div id="firstcomponent"> <h1>I am a title.</h1> <a> written by {{ author }} </a> </div> </template> <script type="text/javascript"> export default { data () { return { author: "微信公眾號 jinkey-love" } } } </script> <style> </style>
duang... 不能按官網文檔那樣子叫我做就做,我得先試試再告訴你,我做完效果是這樣子的,希望觀眾做完也是這樣子。(迷之微笑 )

然后在 App.vue 使用組件 ( 因為在 index.html
里面定義了<div id="app"></div>所以就以這個組件作為主入口,方便 )
第一步,引入。在<script></script>
標簽內的第一行寫
import firstcomponent from './component/firstcomponent.vue'
第二步,注冊。在<script></script>
標簽內的 data 代碼塊后面加上 components: { firstcomponent }。記得中間加英文逗號!!!
export default { data () { return { msg: 'Hello Vue!' } }, components: { firstcomponent } }
第三步,使用。
在<template></template>
內加上<firstcomponent></firstcomponent>
<template>
<div id="app">

<h1>{{ msg }}</h1>
<firstcomponent></firstcomponent>
</div>
</template>
完成后的代碼:

這時候看看瀏覽器上的 http://localhost:8080/
頁面(之前打開過就會自動刷新),如果你沒看到效果是因為你沒有對 App.vue
和 firstcomponent.vue
進行保存操作,保存后頁面會自動刷新。

使用路由搭建單頁應用
之前已經通過命令安裝了vue-router
cnpm install vue-router --save
在webpack.config.js
加入別名
resolve: {
alias: {vue: 'vue/dist/vue.js'} }
為什么要加 alias 配置項?其作用可以在文檔中有相應的描述:

修改完之后的webpack.config.js
是這樣子的:
var path = require('path') var webpack = require('webpack') module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'build.js' }, resolveLoader: { root: path.join(__dirname, 'node_modules'), }, module: { loaders: [ { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.vue$/, loader: 'vue' }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.js$/, loader: 'babel', exclude: /node_modules/ }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.(png|jpg|gif|svg)$/, loader: 'file', query: { name: '[name].[ext]?[hash]' } } ] }, resolve: { alias: {vue: 'vue/dist/vue.js'} }, devServer: { historyApiFallback: true, noInfo: true }, devtool: '#eval-source-map' } if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ]) }
再按之前的方法寫一個組件 secondcomponent.vue
<template> <div id="secondcomponent"> <h1>I am another page</h1> <a> written by {{ author }} </a> <p> 感謝 <a href="https://github.com/showonne">showonne</a>大神的技術指導</p> </div> </template> <script> export default { data() { return { author: "微信公眾號 jinkey-love", articles: [], } } } } </script> <style> </style>
這時候修改 main.js,引入並注冊 vue-router
import VueRouter from "vue-router"; Vue.use(VueRouter);
並且配置路由規則和 app 啟動配置項加上 router,舊版的 router.map 方法在 vue-router 2.0
已經不能用了。修改后的main.js
如下:
import Vue from 'vue' import App from './App.vue' import VueRouter from "vue-router"; import VueResource from 'vue-resource' //開啟debug模式 Vue.config.debug = true; Vue.use(VueRouter); Vue.use(VueResource); // 定義組件, 也可以像教程之前教的方法從別的文件引入 const First = { template: '<div><h2>我是第 1 個子頁面</h2></div>' } import secondcomponent from './component/secondcomponent.vue' // 創建一個路由器實例 // 並且配置路由規則 const router = new VueRouter({ mode: 'history', base: __dirname, routes: [ { path: '/first', component: First }, { path: '/second', component: secondcomponent } ] }) // 現在我們可以啟動應用了! // 路由器會創建一個 App 實例,並且掛載到選擇符 #app 匹配的元素上。 const app = new Vue({ router: router, render: h => h(App) }).$mount('#app')
這樣子改完再打開瀏覽器看看。

點擊那兩個鏈接試試,會發現<router-view class="view"></router-view>
的內容已經展示出來,同時注意瀏覽器地址已經變更。

另外,也可以把 App.vue 的內容寫在 main.js 也是可以的不過不建議這么做

如果你使用 vue1.0和0.7版本的 vue-router,請參照下面這個教程, 他整個系列都不錯的,當然僅限於 vue1.0 :
給頁面加點動態數據
這時候的頁面都是靜態的(數據在寫程序的時候已經固定了不能修改),而每個應用基本上都會請求外部數據以動態改變頁面內容。對應有一個庫叫 vue-resource
幫我們解決這個問題。
使用命令行安裝
cnpm install vue-resource --save
在 main.js 引入並注冊 vue-resource
:
import VueResource from 'vue-resource' Vue.use(VueResource);
我們在 secondcomponent.vue 上來動態加載數據
添加一個列表:
<ul>
<li v-for="article in articles">
{{article.title}}
</li>
</ul>
在 data 里面加入數組 articles 並賦值為[]
然后在 data 后面加入加入鈎子函數 mounted
(詳細請參照官方文檔關於 vue 生命周期的解析),data 和 mount 中間記得記得加逗號
mounted: function() { this.$http.jsonp('https://api.douban.com/v2/movie/top250?count=10', {}, { headers: { }, emulateJSON: true }).then(function(response) { // 這里是處理正確的回調 this.articles = response.data.subjects // this.articles = response.data["subjects"] 也可以 }, function(response) { // 這里是處理錯誤的回調 console.log(response) }); }
這里使用的是豆瓣的公開 GET 接口,如果接口是跨域的 POST 請求,則需要在服務器端配置:
Access-Control-Allow-Origin: *
這時候運行看看。等一會接口返回數據,咦,數據加載出來了,棒棒噠 !

更多 vue-router
的使用方法可以看
vue-router 0.7
http://m.doc00.com/doc/1001004eg
vue-router 2.0
http://router.vuejs.org/zh-cn/index.html
來拯救如此難看的界面
組件、雙向綁定、路由、數據請求等基本特性都能用了,寫到這里一個單頁應用基本上成型了。但是,這幾面也太 TM 難看了吧。自己寫 UI 框架太費勁?那就上網找一個吧。
本來想給大家介紹 Vux 的,因為他用的是微信的 WeUI 設計規范,對於開發微信小程序或者微信內的網頁非常和諧,但由於寫這篇文章的時候 Vux 還不支持 vue2.0,只能用別的框架了。
命令行安裝 ElementUI (此處某公司的人應該發紅包了...)
cnpm install element-ui@next -S
然后在 main.js 引入並注冊
import Element from 'element-ui' import 'element-ui/lib/theme-default/index.css' Vue.use(Element)
保存,這時候程序報錯
Uncaught Error: Module parse failed: /Users/**/Desktop/vue2/node_modules/.1.0.0-rc.5@element-ui/lib/theme-default/index.css Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type.
官網文檔又有坑了,安裝教程也不跟我們說這一步,當我們都是高手了...
報錯是由於我們引入了index.css
這個 CSS 文件,但是 webpack 打包的時候無法識別並轉換成 js,所以就需要配置才能讀取 css 和字體文件,運行命令安裝下面三個東西(如果之前安裝過就不需要了)
cnpm install style-loader --save-dev
cnpm install css-loader --save-dev
cnpm install file-loader --save-dev
在 webpack.config.js
中的 loaders 數組加入以下配置,記得該加逗號的地方加逗號!
{
test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.css$/, loader: "style!css" }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.(eot|woff|woff2|ttf)([\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\?]?.*)$/, loader: "file" }
修改完的 webpack.config.js
如下
var path = require('path') var webpack = require('webpack') module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'build.js' }, resolveLoader: { root: path.join(__dirname, 'node_modules'), }, module: { loaders: [ { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.vue$/, loader: 'vue' }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.js$/, loader: 'babel', exclude: /node_modules/ }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.css$/, loader: "style!css" }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.(eot|woff|woff2|ttf)([\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\?]?.*)$/, loader: "file" }, { test: /\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\.(png|jpg|gif|svg)$/, loader: 'file', query: { name: '[name].[ext]?[hash]' } } ] }, resolve: { alias: {vue: 'vue/dist/vue.js'} }, devServer: { historyApiFallback: true, noInfo: true }, devtool: '#eval-source-map' } if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }) ]) }
給豆瓣的電影列表套個衣服(樣式) :
<el-card class="box-card">
<div slot="header" class="clearfix">
<h1 style="line-height: 36px; color: #20A0FF">豆瓣電影排行榜</h2>
</div>
<div v-for="article in articles" class="text item">
{{article.title}}
</div>
</el-card>
打開瀏覽器,輸入網址:


列表比之前漂亮多了,你還可以參照 ElementUI 的文檔使用更多組件樣式
編譯
npm run build
又報錯了...orz
ERROR in build.js from UglifyJs
SyntaxError: Unexpected token punc «(», expected punc «:» [build.js:32001,6]
解決辦法(21061019 showonne 提交 PR 已合並到主分支)
cnpm install babel-preset-es2015 --save-dev
cnpm install babel-preset-stage-0 --save-dev
然后在項目目錄下創建一個.babelrc
文件,內容如下:
{
presets: ['es2015', 'stage-0'] }
或者在webpack.config.js
中這里
{
test: /\\\\.js$/, loader: 'babel', exclude: /node_modules/ }
加入 presets 配置,修改成下面醬紫:
{
test: /\\\\.js$/, loader: 'babel', exclude: /node_modules/, query: {presets: ['es2015', 'stage-0'] }
再次執行 npm run build
就可以了,后來發現直接運行 webpack 命令也是可以打包的
webpack --color --progress
接着把 index.html 和整個 dist 目錄丟到服務器就可以了。
如果你覺得這篇文章寫得好,不需要打賞,你可以下載我朋友做的一個閱讀工具,可以訂閱公眾號和簡書、也可以看大神分享的優秀文章。
下載地址:https://itunes.apple.com/us/app/you-duuread-zhi-gei-xiang/id1175225244
作者:JinkeyBlog
鏈接:http://www.jianshu.com/p/5ba253651c3b
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。