Vue.js入門教程
參考文獻
- Vue-Cli webpack打包入門:http://www.cnblogs.com/keepfool/p/5678427.html
- Vue中文文檔:https://cn.vuejs.org/v2/guide/index.html
- Vue-cli webpack打包實戰(zhàn):https://segmentfault.com/a/1190000008143264
- over
安裝Vue.js
- 直接下載并用
<script>
標簽引入壳繁,Vue
會被注冊為一個全局變量媳溺。重要提示:在開發(fā)時使用開發(fā)版本嵌戈,http://cn.vuejs.org/guide/installation.html- 可以從 jsdelivr 或 cdnjs 獲让癖谩(版本更新可能略滯后)赠涮。
- 有些環(huán)境溃列,如 Google Chrome Apps例证,強制應用內容安全策略 (CSP) 咬荷,不能使用
new Function()
對表達式求值冠句。這時可以用 CSP 兼容版本。
NPM
使用Vue.js構建大型應用時推薦使用nmp安裝幸乒,npm能很好的和諸如 Webpack 或者Browserify 的
CommonJS
模塊打包器配合使用懦底。Vue.js也提供配套工具開發(fā)單文件組件。#最新穩(wěn)定版本 $ npm install vue # 最新穩(wěn)定 CSP 兼容版本 $ npm install vue@csp
命令行工具
Vue.js 提供一個官方命令行工具,可用于快速搭建大型單頁應用聚唐。該工具提供開箱即用的構建工具配置丐重,帶來現(xiàn)代化的前端開發(fā)流程。只需一分鐘即可啟動帶熱重載杆查、保存時靜態(tài)檢查以及可用于生產環(huán)境的構建配置的項目:
# 全局安裝 vue-cli, #/Users/gaolong/.nvm/versions/node/v5.7.0/bin/vue -> /Users/gaolong/.nvm/versions/node/v5.7.0/lib/node_modules/vue-cli/bin/vue /Users/gaolong/.nvm/versions/node/v5.7.0/lib $ npm install -g vue-cli # 創(chuàng)建一個基于 "webpack" 模板的新項目 $ vue init webpack my-project # 安裝依賴扮惦,走你 $ cd my-project $ npm install $ npm run dev
開發(fā)版本
重要:發(fā)布到 NPM 上的 CommonJS 包 (
vue.common.js
) 只在發(fā)布新版本時簽入 master 分支,所以這些文件在 dev 分支下跟穩(wěn)定版本是一樣的亲桦。想使用 GitHub 上最新的源碼崖蜜,需要自己編譯:git clone https://github.com/vuejs/vue.git node_modules/vue cd node_modules/vue npm install npm run build
vue-cli wepack打包
參考文獻:https://loulanyijian.github.io/vue-cli-doc-Chinese/structure.html
兩種方式
使用vue-webpack-simple模板
使用vue-webpack模板
安裝vue-cli $ npm install -g vue-cli
生成項目
$ vue init webpack-simple my-webpack-simple-demo webpack-simple是項目模板的名稱 目錄結構 ├─.babelrc // babel配置文件 ├─.gitignore ├─index.html // 主頁 ├─package.json // 項目配置文件 ├─README.md ├─webpack.config.js // webpack配置文件 ├─dist // 發(fā)布目錄 │ ├─.gitkeep ├─src // 開發(fā)目錄 │ ├─App.vue // App.vue組件 │ ├─main.js // 預編譯入口 編譯的輸入和輸出是定義在webpack.config.js文件中的 webpack.config.js內容還是比較好理解的,它采用了CommonJS的寫法客峭,entry節(jié)點配置了編譯入口豫领,output節(jié)點配置了輸出。 這段entry和output配置的含義是:編譯src/main.js文件舔琅,然后輸出到dist/build.js文件等恐。
安裝項目依賴
$ cd my-webpack-simple-demo $ npm install 運行項目 npm run dev 編譯項目 npm run build
over
Vue.js體驗
介紹
聲明式渲染
<div id="app"> {{ message }} </div> var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } })
條件和循環(huán)
<div id="app-2"> <span v-bind:title="message"> 鼠標懸停幾秒鐘查看此處動態(tài)綁定的提示信息! </span> </div> 指令帶有前綴 v-备蚓,以表示它們是 Vue 提供的特殊特性 <div id="app-3"> <p v-if="seen">現(xiàn)在你看到我了</p> </div> var app3 = new Vue({ el: '#app-3', data: { seen: true } }) <div id="app-4"> <ol> <li v-for="todo in todos"> {{ todo.text }} </li> </ol> </div> var app4 = new Vue({ el: '#app-4', data: { todos: [ { text: '學習 JavaScript' }, { text: '學習 Vue' }, { text: '整個牛項目' } ] } })
處理用戶輸入
<div id="app-5"> <p>{{ message }}</p> <button v-on:click="reverseMessage">逆轉消息</button> </div> var app5 = new Vue({ el: '#app-5', data: { message: 'Hello Vue.js!' }, methods: { reverseMessage: function () { this.message = this.message.split('').reverse().join('') } } }) methods和data平級
組件化應用構建
在 Vue 里课蔬,一個組件本質上是一個擁有預定義選項的一個 Vue 實例 import Vue from 'vue' Vue.component('todo-item', { // todo-item 組件現(xiàn)在接受一個 // "prop",類似于一個自定義特性星著。 // 這個 prop 名為 todo购笆。 props: ['todo'], template: '<li>{{ todo.text }}</li>' }) <div id="app-7"> <ol> <!-- 現(xiàn)在我們?yōu)槊總€ todo-item 提供 todo 對象 todo 對象是變量,即其內容可以是動態(tài)的虚循。 我們也需要為每個組件提供一個“key”同欠,稍后再 作詳細解釋。 --> <todo-item v-for="item in groceryList" v-bind:todo="item" v-bind:key="item.id"> </todo-item> </ol> </div> var app7 = new Vue({ el: '#app-7', data: { groceryList: [ { id: 0, text: '蔬菜' }, { id: 1, text: '奶酪' }, { id: 2, text: '隨便其它什么人吃的東西' } ] } })
over
Vue實例
創(chuàng)建vue實例
實例生命周期鉤子
imageover
模板語法
插值
文本 <span>Message: {{ msg }}</span> <span v-once>這個將不會改變: {{ msg }}</span> 一次性插值 原始HTML 輸出真正的html <p>Using mustaches: {{ rawHtml }}</p> <p>Using v-html directive: <span v-html="rawHtml"></span></p> 特性 Mustache 語法不能作用在 HTML 特性上横缔,遇到這種情況應該使用 v-bind 指令 <div v-bind:id="dynamicId"></div> 使用JavaScript表達式 對于所有的數據綁定铺遂,Vue.js 都提供了完全的 JavaScript 表達式支持。 {{ number + 1 }} {{ ok ? 'YES' : 'NO' }} {{ message.split('').reverse().join('') }} <div v-bind:id="'list-' + id"></div> 單個表達式 指令 指令 (Directives) 是帶有 v- 前綴的特殊屬性 <p v-if="seen">現(xiàn)在你看到我了</p> 參數 <a v-bind:href="url">...</a> 在這里 href 是參數茎刚,告知 v-bind 指令將該元素的 href 屬性與表達式 url 的值綁定襟锐。 <a v-on:click="doSomething">...</a> 這里參數是監(jiān)聽的事件名 修飾符 <form v-on:submit.prevent="onSubmit">...</form> 修飾符 (Modifiers) 是以半角句號 . 指明的特殊后綴,用于指出一個指令應該以特殊方式綁定 縮寫 vi-bind縮寫 <!-- 完整語法 --> <a v-bind:href="url">...</a> <!-- 縮寫 --> <a :href="url">...</a> <!-- 完整語法 --> <a v-on:click="doSomething">...</a> <!-- 縮寫 --> <a @click="doSomething">...</a>
over
計算屬性和偵聽器
計算屬性
使用計算屬性 <div id="example"> <p>Original message: "{{ message }}"</p> <p>Computed reversed message: "{{ reversedMessage }}"</p> </div> var vm = new Vue({ el: '#example', data: { message: 'Hello' }, computed: { // 計算屬性的 getter reversedMessage: function () { // `this` 指向 vm 實例 return this.message.split('').reverse().join('') } } }) 使用函數 <p>Reversed message: "{{ reversedMessage() }}"</p> // 在組件中 methods: { reversedMessage: function () { return this.message.split('').reverse().join('') } } 偵聽屬性 Vue 提供了一種更通用的方式來觀察和響應 Vue 實例上的數據變動:偵聽屬性 <div id="demo">{{ fullName }}</div> var vm = new Vue({ el: '#demo', data: { firstName: 'Foo', lastName: 'Bar', fullName: 'Foo Bar' }, watch: { firstName: function (val) { this.fullName = val + ' ' + this.lastName }, lastName: function (val) { this.fullName = this.firstName + ' ' + val } } }) 計算屬性setter // ... computed: { fullName: { // getter get: function () { return this.firstName + ' ' + this.lastName }, // setter set: function (newValue) { var names = newValue.split(' ') this.firstName = names[0] this.lastName = names[names.length - 1] } } } // ...
偵聽器
<div id="watch-example"> <p> Ask a yes/no question: <input v-model="question"> </p> <p>{{ answer }}</p> </div> <!-- 因為 AJAX 庫和通用工具的生態(tài)已經相當豐富膛锭,Vue 核心代碼沒有重復 --> <!-- 提供這些功能以保持精簡粮坞。這也可以讓你自由選擇自己更熟悉的工具。 --> <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script> <script> var watchExampleVM = new Vue({ el: '#watch-example', data: { question: '', answer: 'I cannot give you an answer until you ask a question!' }, watch: { // 如果 `question` 發(fā)生改變初狰,這個函數就會運行 question: function (newQuestion, oldQuestion) { this.answer = 'Waiting for you to stop typing...' this.getAnswer() } }, methods: { // `_.debounce` 是一個通過 Lodash 限制操作頻率的函數莫杈。 // 在這個例子中,我們希望限制訪問 yesno.wtf/api 的頻率 // AJAX 請求直到用戶輸入完畢才會發(fā)出奢入。想要了解更多關于 // `_.debounce` 函數 (及其近親 `_.throttle`) 的知識筝闹, // 請參考:https://lodash.com/docs#debounce getAnswer: _.debounce( function () { if (this.question.indexOf('?') === -1) { this.answer = 'Questions usually contain a question mark. ;-)' return } this.answer = 'Thinking...' var vm = this axios.get('https://yesno.wtf/api') .then(function (response) { vm.answer = _.capitalize(response.data.answer) }) .catch(function (error) { vm.answer = 'Error! Could not reach the API. ' + error }) }, // 這是我們?yōu)榕卸ㄓ脩敉V馆斎氲却暮撩霐? 500 ) } }) </script>
over
Class與Style綁定
綁定HTML Class
對象語法 我們可以傳給 v-bind:class 一個對象,以動態(tài)地切換 class: <div class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }"> </div> data: { isActive: true, hasError: false }結果渲染為 <div class="static active"></div> 利用計算屬性渲染 <div v-bind:class="classObject"></div> data: { isActive: true, error: null }, computed: { classObject: function () { return { active: this.isActive && !this.error, 'text-danger': this.error && this.error.type === 'fatal' } } } 數組語法 可以把一個數組傳給 v-bind:class,以應用一個 class 列表: <div v-bind:class="[activeClass, errorClass]"></div> data: { activeClass: 'active', errorClass: 'text-danger' } 綁定在組件上
?
綁定內聯(lián)樣式
<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div> data: { activeColor: 'red', fontSize: 30 } 綁定到一個樣式對象上: <div v-bind:style="styleObject"></div> data: { styleObject: { color: 'red', fontSize: '13px' } } 數組語法 <div v-bind:style="[baseStyles, overridingStyles]"></div> 自動添加前綴 多重值
?
over
條件渲染
1. v-if <h1 v-if="ok">Yes</h1> 或者 <h1 v-if="ok">Yes</h1> <h1 v-else>No</h1> 新增v-else-if <div v-if="type === 'A'"> A </div> <div v-else-if="type === 'B'"> B </div> <div v-else-if="type === 'C'"> C </div> <div v-else> Not A/B/C </div> 2.v-show 3.v-if&v-for
列表渲染
v-for
<ul id="example-1"> <li v-for="item in items"> {{ item.message }} </li> </ul> <ul id="example-2"> <li v-for="(item, index) in items"> {{ parentMessage }} - {{ index }} - {{ item.message }} </li> </ul> 用of代替in <div v-for="item of items"></div> <ul id="v-for-object" class="demo"> <li v-for="value in object"> {{ value }} </li> </ul> 第三個參數為索引 <div v-for="(value, key, index) in object"> {{ index }}. {{ key }}: {{ value }} </div>
?
over
事件處理
表單輸入綁定
組件
使用組件
1.全局注冊 2.局部注冊 3.DOM模板解析 <option> <ul>关顷、<ol>糊秆、<table>、<select> 使用is <table> <tr is="my-row"></tr> </table> 4.data必須是函數 5.組件組合
Prop
1.使用Prop傳遞數據 Vue.component('child', { // 聲明 props props: ['message'], // 就像 data 一樣议双,prop 也可以在模板中使用 // 同樣也可以在 vm 實例中通過 this.message 來使用 template: '<span>{{ message }}</span>' }) 傳入普通字符串 <child message="hello!"></child> 2.HTML 特性是不區(qū)分大小寫的痘番。所以,當使用的不是字符串模板時聋伦,camelCase (駝峰式命名) 的 prop 需要轉換為相對應的 kebab-case (短橫線分隔式命名): Vue.component('child', { // 在 JavaScript 中使用 camelCase props: ['myMessage'], template: '<span>{{ myMessage }}</span>' }) <!-- 在 HTML 中使用 kebab-case --> <child my-message="hello!"></child> 3. 動態(tài)Prop <div> <input v-model="parentMsg"> <br> <child v-bind:my-message="parentMsg"></child> </div> new Vue({ el: '#prop-example-2', data: { parentMsg: 'Message from parent' } }) 可以使用 v-bind 的縮寫語法 <child :my-message="parentMsg"></child> child是子組件夫偶。 4.字面量語法vc動態(tài)語法 <!-- 傳遞真正的數值 --> <comp v-bind:some-prop="1"></comp> <!-- 傳遞了一個字符串 "1" --> <comp some-prop="1"></comp> 5.單向數據流 Prop 是單向綁定的:當父組件的屬性變化時,將傳導給子組件觉增,但是反過來不會兵拢。這是為了防止子組件無意間修改了父組件的狀態(tài),來避免應用的數據流變得難以理解逾礁。 每次父組件更新時说铃,子組件的所有 prop 都會更新為最新值。這意味著你不應該在子組件內部改變 prop嘹履。 子組件定義局部變量 props: ['initialCounter'], data: function () { return { counter: this.initialCounter } } 子組件定義計算屬性 props: ['size'], computed: { normalizedSize: function () { return this.size.trim().toLowerCase() } } 6.Prop驗證 Vue.component('example', { props: { // 基礎類型檢測 (`null` 指允許任何類型) propA: Number, // 可能是多種類型 propB: [String, Number], // 必傳且是字符串 propC: { type: String, required: true }, // 數值且有默認值 propD: { type: Number, default: 100 }, // 數組/對象的默認值應當由一個工廠函數返回 propE: { type: Object, default: function () { return { message: 'hello' } } }, // 自定義驗證函數 propF: { validator: function (value) { return value > 10 } } } })
?
非Prop特性
自定義事件
image子組件與父組件通訊 1.使用v-on綁定自定義事件 每個 Vue 實例都實現(xiàn)了事件接口腻扇,即: 使用 $on(eventName) 監(jiān)聽事件 使用 $emit(eventName, optionalPayload) 觸發(fā)事件 <div id="counter-event-example"> <p>{{ total }}</p> <button-counter v-on:increment="incrementTotal"></button-counter> <button-counter v-on:increment="incrementTotal"></button-counter> </div> Vue.component('button-counter', { template: '<button v-on:click="incrementCounter">{{ counter }}</button>', data: function () { return { counter: 0 } }, methods: { incrementCounter: function () { this.counter += 1 this.$emit('increment') } }, }) new Vue({ el: '#counter-event-example', data: { total: 0 }, methods: { incrementTotal: function () { this.total += 1 } } }) //帶參數情況 methods: { handleSendMessage: function () { this.$emit('message', { message: this.message }) } } 2.給組件綁定原生事件 <my-component v-on:click.native="doTheThing"></my-component> 3. .sync修飾符 當一個子組件改變了一個帶 .sync 的 prop 的值時,這個變化也會同步到父組件中所綁定的值砾嫉。 4.使用自定義的表單輸入組件 5.自定義組件的v-model 6.非父子組件的通訊 var bus = new Vue() // 觸發(fā)組件 A 中的事件 bus.$emit('id-selected', 1) // 在組件 B 創(chuàng)建的鉤子中監(jiān)聽事件 bus.$on('id-selected', function (id) { // ... })
使用插槽分發(fā)內容
1. 單個插槽 2.具名插槽 3.作用域插槽 4.解構
動態(tài)組件
?
其他雜項
動畫&過渡
Vue在插入幼苛、更新或移除DOM時,提供多種不同方法應用效果過渡
Vue 提供了 transition 的封裝組件焕刮,在下列情形中舶沿,可以給任何元素和組件添加 entering/leaving 過渡 條件渲染 (使用 v-if) 條件展示 (使用 v-show) 動態(tài)組件 組件根節(jié)點 <div id="demo"> <button v-on:click="show = !show"> Toggle </button> <transition name="fade"> <p v-if="show">hello</p> </transition> </div> new Vue({ el: '#demo', data: { show: true } }) .fade-enter-active, .fade-leave-active { transition: opacity .5s; } .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ { opacity: 0; } 過渡類名 在進入/離開的過渡中,會有 6 個 class 切換配并。 具體參考Vue官方文檔過渡動畫這一章節(jié) css過渡 css動畫 自定義過渡類名 enter-class enter-active-class enter-to-class (2.1.8+) leave-class leave-active-class leave-to-class (2.1.8+)
狀態(tài)過渡
?
可復用性&組合
混入
混入 (mixins) 是一種分發(fā) Vue 組件中可復用功能的非常靈活的方式括荡。混入對象可以包含任意組件選項溉旋。當組件使用混入對象時畸冲,所有混入對象的選項將被混入該組件本身的選項。 // 定義一個混入對象 var myMixin = { created: function () { this.hello() }, methods: { hello: function () { console.log('hello from mixin!') } } } // 定義一個使用混入對象的組件 var Component = Vue.extend({ mixins: [myMixin] }) var component = new Component() // => "hello from mixin!" 當組件和混入對象含有同名選項時观腊,這些選項將以恰當的方式混合邑闲。 全局混入
?
自定義指令
渲染函數& JSX
Vue 推薦在絕大多數情況下使用 template 來創(chuàng)建你的 HTML。
?
插件
過濾器
工具
規(guī)奈嘤停化
官方路由
推薦使用官方 vue-router 庫:
?
整合第三方路由
如果有非常喜歡的第三方路由苫耸,如 Page.js 或者 Director,整合很簡單婶溯。這有個用了 Page.js 的復雜示例。
over
vue-router
vue-router
參考文獻:https://router.vuejs.org/zh-cn/essentials/named-routes.html
vue-router的基本使用方法
在router 、index.js文件中定義router
這里有個坑迄委,定義path的時候不能和其他path重名褐筛,path就是展示在瀏覽器中的路由。
然后使用this.$router.push({name: Message})
代碼
import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import Test from '@/components/Test' import Message from '@/components/Message' // const Test = resolve => require(['../components/Test.vue'], resolve) // const HelloWorld = resolve => require(['../components/HelloWorld.vue'], resolve) Vue.use(Router) // let routes = [ // ] export default new Router({ routes: [ { path: '/', name: 'HelloWorld', component: HelloWorld }, { path: '/test', name: 'Test', component: Test }, { path: '/message', name: 'Message', component: Message } ] })
//Message.vue
methods: {
routeToTest () {
this.$router.push({name: 'Test'})
}
}或者使用
<router-link to="/test">前往test頁路由</router-link>4. over
Vue API
JQuery教程
jquery語法
語法
1. 簡寫 $(function(){ // 開始寫 jQuery 代碼... }); 2.標簽 3.#id選擇器 4..class選擇器 5. 更多: $(*) $(this) $("p.intro") $("p:first") $("ul li:first") $("ul li:first-child") $("[href]") $("a[traget='_black']") 6.獨立使用jquery <head> <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"> </script> <script src="my_jquery_functions.js"></script> </head> 7. $(":button")
效果
1. jquery隱藏/顯示 $("p").hide() $("p").show() $("p").toggle() $("p").fadeIn() $("p").fadeOut() $("p").fadeToggle() 2. 淡入淡出 3. 滑動 4. 動畫 $(selector).animate({params},speed,callback); $(selector).stop(stopAll,goToEnd); 5. 停止動畫 6. callback 7. 鏈
jQuery HTML
text() html() val() 回調方法 1. 捕獲 2. 設置 3. 添加元素 4. 刪除元素 append()叙身、prepend()渔扎、after()、before() remove()信轿、empty()晃痴、 5. css類 addClass()、removeClass()财忽、toggleClass() $("button").click(function(){ $("h1,h2,p").addClass("blue"); $("div").addClass("important"); }); 6. css()方法 7. 尺寸
jQuery遍歷
jquery祖先 $(document).ready(function(){ $("span").parent(); }); 后代 children() 同胞 siblings()倘核、next()、nextAll()即彪、nextUntil()\pev() 過濾 first()紧唱、last()、eq()隶校、filter()漏益、not()、
?
over