javascript
另外幾個常見的工具庫:react.js /angular.jscss
官方網站:html
英文:https://vuejs.org/vue
官方文檔:https://cn.vuejs.org/v2/guide/java
vue.js目前有1.x、2.x和3.x 版本,咱們學習2.x版本的。node
在github下載:python
在官網下載地址: https://cn.vuejs.org/v2/guide/installation.htmlreact
vue的引入相似於jQuery,開發中可使用開發版本vue.js,產品上線要換成vue.min.js。jquery
下圖是github網站下載的vue.js目錄
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="js/vue.js"></script> <script> window.onload = function(){ // vue.js的代碼開始於一個Vue對象。因此每次操做數據都要聲明Vue對象開始。 var vm = new Vue({ el:'#app', // 設置當前vue對象要控制的標籤範圍。 data:{ // data是將要展現到HTML標籤元素中的數據。 message: 'hello world!', } }); } </script> </head> <body> <div id="app"> <!-- {{ message }} 表示把vue對象裏面data屬性中的對應數據輸出到頁面中 --> <!-- 在雙標籤中顯示數據要經過{{ }}來完成 --> <p>{{ message }}</p> </div> </body> </html>
總結:
1. vue的使用要從建立Vue對象開始 var vm = new Vue(); 2. 建立vue對象的時候,須要傳遞參數,是json對象,json對象對象必須至少有兩個屬性成員 var vm = new Vue({ el:"#app", data: { 數據變量:"變量值", 數據變量:"變量值", 數據變量:"變量值", }, }); el:設置vue能夠操做的html內容範圍,值通常就是css的id選擇器。 data: 保存vue.js中要顯示到html頁面的數據。 3. vue.js要控制器的內容外圍,必須先經過id來設置。 <div id="app"> <h1>{{message}}</h1> <p>{{message}}</p> </div>
MVVM 是Model-View-ViewModel 的縮寫,它是一種基於前端開發的架構模式。
Model 指代的就是vue對象的data屬性裏面的數據。這裏的數據要顯示到頁面中。
View 指代的就是vue中數據要顯示的HTML頁面,在vue中,也稱之爲「視圖模板」 。
ViewModel 指代的是vue.js中咱們編寫代碼時的vm對象了,它是vue.js的核心,負責鏈接 View 和 Model,保證視圖和數據的一致性,因此前面代碼中,data裏面的數據被顯示中p標籤中就是vm對象自動完成的。
MVVM:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.min.js"></script> <script> window.onload = function(){ // 建立vm對象 var vm = new Vue({ el: "#app", data: { name:"大標題", age:16, }, }) } </script> </head> <body> <div id="app"> <!-- 在雙標籤中顯示數據要經過{{ }}來完成 --> <h1>{{name}}</h1> <p>{{age}}</p> <!-- 在表單輸入框中顯示數據要使用v-model來完成,模板語法的時候,咱們會詳細學習 --> <input type="text" v-model="name"> </div> </body> </html>
在瀏覽器中能夠在 console.log經過 vm對象能夠直接訪問el和data屬性,甚至能夠訪問data裏面的數據
console.log(vm.$el) # #box vm對象能夠控制的範圍
console.log(vm.$data); # vm對象要顯示到頁面中的數據
console.log(vm.$data.message); # 訪問data裏面的數據
console.log(vm.message);# 這個 message就是data裏面聲明的數據,也可使用 vm.變量名顯示其餘數據,message只是舉例.
1. 若是要輸出data裏面的數據做爲普通標籤的內容,須要使用{{ }} 用法: vue對象的data屬性: data:{ name:"小明", } 標籤元素: <h1>{{ name }}</h1> 2. 若是要輸出data裏面的數據做爲表單元素的值,須要使用vue.js提供的元素屬性v-model 用法: vue對象的data屬性: data:{ name:"小明", } 表單元素: <input v-model="name"> 使用v-model把data裏面的數據顯示到表單元素之後,一旦用戶修改表單元素的值,則data裏面對應數據的值也會隨之發生改變,甚至,頁面中凡是使用了這個數據都會發生變化。
在表單輸入框中顯示數據要使用v-model來完成數據顯示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.min.js"></script> <script> window.onload = function(){ var vm = new Vue({ el:"#app", data:{ str1: "hello", num: 20, url1: "http://www.baidu.com", url2: "http://www.taobao.com" } }) } </script> </head> <body> <p>{{ str1 }}</p> <p>{{ str1.split("").reverse().join("") }}</p> <p>num和num2中比較大的數是:{{ num>num2? num:num2 }}</p> <input type="text" v-model="name"> </body> </html>
雙花括號僅用輸出文本內容,若是要輸出html代碼,則不能使用這個.要使用v-html來輸出.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div class="app"> <h1>{{title}}</h1> <h3>{{url1}}</h3> {{img}}<br> <span v-html="img"></span> </div> <script> let vm = new Vue({ el:".app", data:{ title:"個人vue", url1:"個人收穫地址", img:'<img src="images/shendan.png">', } }) </script> </body> </html>
1. 能夠在普通標籤中使用{{ }} 或者 v-html 來輸出data裏面的數據 <h1>{{message}}</h1> 2. 能夠在表單標籤中使用v-model屬性來輸出data裏面的數據,同時還能夠修改data裏面的數據 <input type="text" v-model="username">
在輸出內容到普通標籤的使用{{ }}
v-model或者v-html等vue提供的屬性,或者 {{}} 都支持js代碼。
<h1>{{str1.split("").reverse().join("")}}</h1> <!-- 3.2 支持js的運算符--> <h1>{{num1+3}}</h1> <!-- 3.3 js還有一種運算符,三元運算符,相似於python裏面的三元表達式 三元運算符的語法: 判斷條件 ? 條件爲true : 條件爲false的結果 python 三元表達式[三目運算符]的語法: a if 條件 else b --> <h1>num1和num2之間進行比較,最大值:{{ num2>num1?num2:num1 }}</h1>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue的快速使用</title> <script src="js/vue.js"></script> </head> <body> <div id="app"> <p>{{url}}</p> <div>{{text}}</div> <div v-html="text"></div> <input v-model="url"> <div>num是{{num%2==0?'偶數':'奇數'}}</div> <div>num的下一個數字:{{num-0+1}}</div> <input type="text" v-model="num"> <div>{{message.split("").reverse().join("")}}</div> <input type="text" v-model="message.split('').reverse().join('')"> </div> <script> var vm = new Vue({ el:"#app", // 設置vue對象控制的標籤範圍 data:{ // vue要操做的數據 url:"http://www.luffycity.com", text:"<h1>大標題</h1>", num: 100, message:"abcdef", } }) </script> </body> </html>
vue快速使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> <script> window.onload = function () { // vue的基本使用分3步: // 1. 使用如下代碼,經過new Vue對象來建立 // 2. 給vue對象傳參數,一個json對象,對象有el屬性綁定html中的一個已經存在的元素標籤 // 3. 經過vue對象的其餘屬性 var vm = new Vue({ el:'#app', data:{ message:'hello , vue', num:100, } }); console.log(vm) } </script> </head> <body> <div id="app"> {{message}} {{num}} </div> </body> </html>
mvvm
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> <script> window.onload = function(){ // vm視圖控制對象,會實時監控,時刻保證data屬性中的數據和html視圖中的內容保持一致: vm = new Vue({ el: "#app", data:{ img: "logo.png", num: 1, content:"<h1>大標題</h1>", url:"http://www.luffycity.com" }, // 事件觸發時調用的方法,或者其餘屬性方法中調用的內部方法 methods:{ show(){ alert("hello") } } }); } // js中也有三元表達式,也叫三元運算符 // 格式: // 條件?true:false; </script> </head> <body> <div id="app"> <input type="text" v-model="img"> {{"圖片地址是:"+img}} <span v-html="img.toLocaleUpperCase()"></span> <img :src="img" alt=""> {{num%2==0?"偶數":"奇數"}}<br> <p v-html="content"></p> <p v-text="content"></p> {{content}}<br> <a v-bind:href="url">路飛</a> <a :href="url">路飛</a> <p @click="show">內容</p> <p v-on:click="show">內容</p> </div> </body> </html>
顯示密碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div id="app"> <input :type="tp" v-model="pwd"> <input type="button" @mousedown="down" @mouseup="up" v-model="message"> </div> <script> var vm = new Vue({ el:"#app", data:{ message:"顯示密碼", pwd:"", tp:"password", }, methods:{ down(){ // 在methods中的子方法裏面要操做data的屬性,可使用this.屬性值 this.tp="text"; this.message="隱藏密碼"; }, up(){ this.tp="password"; this.message="顯示密碼"; } } }) </script> </body> </html>
指令 (Directives) 是帶有「v-」前綴的特殊屬性。每個指令在vue中都有固定的做用。
在vue中,提供了不少指令,經常使用的有:v-if、v-model、v-for等等。
指令會在vm對象的data屬性的數據發生變化時,會同時改變元素中的其控制的內容或屬性。
由於vue的歷史版本緣由,因此有一部分指令都有兩種寫法:
vue1.x寫法 vue2.x的寫法
v-html ----> {{ 普通文本 }} # vue2.x 也支持v-html,v-text,輸出html代碼的內容
v-bind:屬性名 ----> :屬性
v-on:事件名 ----> @事件名
格式:
<標籤名 :標籤屬性="data屬性"></標籤名>
<p :title="str1">{{ str1 }}</p> <!-- 也可使用v-html顯示雙標籤的內容,{{ }} 是簡寫 --> <a :href="url2">淘寶</a> <a v-bind:href="url1">百度</a> <!-- v-bind是vue1.x版本的寫法 -->
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div id="index"> <img :src="url" :alt="title"><br> <input :type="type" placeholder="請輸入wifi密碼"> <button @click="type='text'">顯示密碼</button> </div> <script> let vm = new Vue({ el:"#index", data:{ url:"https://www.luffycity.com/static/img/head-logo.a7cedf3.svg", title:"路飛學成", type:"password" } }) </script> </body> </html>
有兩種事件操做的寫法,@事件名 和 v-on:事件名
<button v-on:click="num++">按鈕</button> <!-- v-on 是vue1.x版本的寫法 --> <button @click="num+=5">按鈕2</button>
1. 使用@事件名來進行事件的綁定 語法: <h1 @click="num++">{{num}}</h1> 2. 綁定的事件的事件名,所有都是js的事件名: @submit ---> onsubmit @focus ---> onfocus ....
步驟:
給vue對象添加操做數據的方法
在標籤中使用指令調用操做數據的方法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div id="box"> <button @click="++num">+</button> <input type="text" v-model="num"> <button @click="sub">-</button> </div> <script> let vm = new Vue({ el:"#box", data:{ num:0, }, methods:{ sub(){ if(this.num<=1){ this.num=0; }else{ this.num--; } } } }) </script> </body> </html> <!--#box>(button+input+button) tab鍵-->
格式: <h1 :class="值">元素</h1> 值能夠是字符串、對象、對象名、數組
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> <style> .box1{ color: red; border: 1px solid #000; } .box2{ background-color: orange; font-size: 32px; } </style> </head> <body> <div id="box"> <!--- 添加class類名,值是一個對象 { class類1:布爾值變量1, class類2:布爾值變量2, } --> <p :class="{box1:myclass1}">一個段落</p> <p @click="myclass3=!myclass3" :class="{box1:myclass2,box2:myclass3}">一個段落</p> </div> <script> let vm1=new Vue({ el:"#box", data:{ myclass1:false, // 布爾值變量若是是false,則不會添加對象的屬性名做爲樣式 myclass2:true, // 布爾值變量若是是true,則不會添加對象的屬性名做爲樣式 myclass3:false, }, }) </script> <!-- 上面的代碼能夠:class的值保存到data裏面的一個變量,而後使用該變量做爲:class的值 --> <style> .box4{ background-color: red; } .box5{ color: green; } </style> <div id="app"> <button @click="mycls.box4=!mycls.box4">改變背景</button> <button @click="mycls.box5=!mycls.box5">改變字體顏色</button> <p :class="mycls">第二個段落</p> </div> <script> let vm2 = new Vue({ el:"#app", data:{ mycls:{ box4:false, box5:true }, } }) </script> <!-- 批量給元素增長多個class樣式類 --> <style> .box6{ background-color: red; } .box7{ color: green; } .box8{ border: 1px solid yellow; } </style> <div id="app2"> <p :class="[mycls1,mycls2]">第三個段落</p> </div> <script> let vm3 = new Vue({ el:"#app2", data:{ mycls1:{ box6:true, box7:true, }, mycls2:{ box8:true, } } }) </script> </body> </html>
1. 給元素綁定class類名,最經常使用的就是第二種。 vue對象的data數據: data:{ myObj:{ complete:true, uncomplete:false, } } html元素: <div class="box" :class="myObj">2222</div> 最終瀏覽器效果: <div class="box complete">2222</div>
格式1:值是json對象,對象寫在元素的:style屬性中 <div :style="{color: activeColor, fontSize: fontSize + 'px' }"></div> 格式2:值是對象變量名,對象在data中進行聲明標籤元素: <div v-bind:style="styleObject"></div> 格式3:值是數組 標籤元素: <div v-bind:style="[style1, style2]"></div>
格式1:值是json對象,對象寫在元素的:style屬性中 標籤元素: <div :style="{color: activeColor, fontSize: fontSize + 'px' }"></div> data數據以下: data: { activeColor: 'red', fontSize: 30 } 格式2:值是對象變量名,對象在data中進行聲明 標籤元素: <div v-bind:style="styleObject"></div> data數據以下: data: { styleObject: { color: 'red', fontSize: '13px' } } 格式3:值是數組 標籤元素: <div v-bind:style="[style1, style2]"></div> data數據以下: data: { style1:{ color:"red" }, style2:{ background:"yellow", fontSize: "21px" } }
新聞列表
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #card{ width: 500px; height: 350px; } .title{ height:50px; } .title span{ width: 100px; height: 50px; background-color:#ccc; display: inline-block; line-height: 50px; /* 設置行和當前元素的高度相等,就可讓文本內容上下居中 */ text-align:center; } .content .list{ width: 500px; height: 300px; background-color: yellow; display: none; } .content .active{ display: block; } .title .current{ background-color: yellow; } </style> <script src="js/vue.js"></script> </head> <body> <div id="card"> <div class="title"> <span @click="num=0" :class="num==0?'current':''">國內新聞</span> <span @click="num=1" :class="num==1?'current':''">國際新聞</span> <span @click="num=2" :class="num==2?'current':''">銀河新聞</span> <!--<span>{{num}}</span>--> </div> <div class="content"> <div class="list" :class="num==0?'active':''">國內新聞列表</div> <div class="list" :class="num==1?'active':''">國際新聞列表</div> <div class="list" :class="num==2?'active':''">銀河新聞列表</div> </div> </div> <script> // 思路: // 當用戶點擊標題欄的按鈕[span]時,顯示對應索引下標的內容塊[.list] // 代碼實現: var card = new Vue({ el:"#card", data:{ num:0, }, }); </script> </body> </html>
vue中提供了兩個指令能夠用於判斷是否要顯示元素,分別是v-if和v-show。
標籤元素: <!-- vue對象最終會把條件的結果變成布爾值 --> <h1 v-if="ok">Yes</h1> data數據: data:{ ok:false // true則是顯示,false是隱藏 }
v-else指令來表示 v-if 的「else 塊」,v-else 元素必須緊跟在帶 v-if 或者 v-else-if 的元素的後面,不然它將不會被識別。
標籤元素: <h1 v-if="ok">Yes</h1> <h1 v-else>No</h1> data數據: data:{ ok:false // true則是顯示,false是隱藏 }
能夠出現多個v-else-if語句,可是v-else-if以前必須有一個v-if開頭。後面能夠跟着v-else,也能夠沒有。
標籤元素: <h1 v-if="num==1">num的值爲1</h1> <h1 v-else-if="num==2">num的值爲2</h1> <h1 v-else>num的值是{{num}}</h1> data數據: data:{ num:2 }
用法和v-if大體同樣,區別在於2點:
v-show後面不能v-else或者v-else-if
v-show隱藏元素時,使用的是display:none來隱藏的,而v-if是直接從HTML文檔中移除元素[ DOM操做中的remove ]
標籤元素: <h1 v-show="ok">Hello!</h1> data數據: data:{ ok:false // true則是顯示,false是隱藏 }
在vue中,能夠經過v-for指令能夠將一組數據渲染到頁面中,數據能夠是數組或者對象。
數據是數組: <ul> <!--book是列表的每個元素--> <li v-for="book in book_list">{{book.title}}</li> </ul> <ul> <!--book是列表的每個元素,index是每一個元素的下標--> <li v-for="book, index in book_list">第{{ index+1}}本圖書:{{book.title}}</li> </ul> <script> var vm1 = new Vue({ el:"#app", data:{ book_list:[ {"id":1,"title":"圖書名稱1","price":200}, {"id":2,"title":"圖書名稱2","price":200}, {"id":3,"title":"圖書名稱3","price":200}, {"id":4,"title":"圖書名稱4","price":200}, ] } }) </script> 數據是對象: <ul> <!--i是每個value值--> <li v-for="value in book">{{value}}</li> </ul> <ul> <!--i是每個value值,j是每個鍵名--> <li v-for="attr, value in book">{{attr}}:{{value}}</li> </ul> <script> var vm1 = new Vue({ el:"#app", data:{ book: { // "attr":"value" "id":11, "title":"圖書名稱1", "price":200 }, }, }) </script>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div id="app"> <button @click="add">+</button> <input type="text" v-model="num"> <button @click="sub">-</button> 單價:{{price}} <p>總計:{{total.toFixed(2)}}</p> </div> <script> var vm = new Vue({ el:"#app", data:{ num: 1, price: 39.8, total: 39.8, }, methods:{ add(){ // 增長數量 this.num = parseInt(this.num) + 1; this.calc(); }, sub(){ // 減小數量 if(this.num<=1){ return; } this.num -= 1; this.calc(); }, calc(){ // 計算總價 this.total = this.price * this.num; } } }) </script> </body> </html>
操做樣式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> <style> .bg{ width: 300px; height: 1000px; } .baitian{ background-color: white; } .heiye{ background-color: #666; } </style> </head> <body> <div id="app" class="bg" :class="{baitian:is_show,heiye:is_show_2}"> <button @click="change">關燈</button> </div> <script> var vm = new Vue({ el:"#app", data:{ is_show:true, is_show_2:false }, methods:{ change(){ if(this.is_show==true){ this.is_show=false; this.is_show_2=true; }else{ this.is_show=true; this.is_show_2=false; } } } }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> <style> .bg{ width: 300px; height: 1000px; } .baitian{ background-color: white; } .heiye{ background-color: #666; } </style> </head> <body> <div id="app" class="bg" :class="{baitian:is_show,heiye:is_show_2}"> <button @click="change">關燈</button> </div> <script> var vm = new Vue({ el:"#app", data:{ is_show:true, is_show_2:false }, methods:{ change(){ if(this.is_show==true){ this.is_show=false; this.is_show_2=true; }else{ this.is_show=true; this.is_show_2=false; } } } }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div id="app"> <div style="width:100px;height:100px;" :style="{backgroundColor:`#6f6`}"></div> <div style="" :style="box"></div> <div style="" :style="[box,box2]"></div> </div> <script> var vm = new Vue({ el:"#app", data:{ box:{ backgroundColor:`#6f6`, width:"100px", height:"100px", }, box2:{ borderRadius:"50px", // borderRadius 邊框圓角 } }, }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #card{ width: 500px; height: 350px; } .title{ height:50px; } .title span{ width: 100px; height: 50px; background-color:#ccc; display: inline-block; line-height: 50px; /* 設置行和當前元素的高度相等,就可讓文本內容上下居中 */ text-align:center; } .content .list{ width: 500px; height: 300px; background-color: yellow; display: none; } .content .active{ display: block; } .title .current{ background-color:yellow; } </style> <script src="js/vue.js"></script> </head> <body> <div id="card"> <div class="title"> <span @mouseover="num=1" :class="num==1?'current':''">國內新聞</span> <span @mouseover="num=2" :class="num==2?'current':''">國際新聞</span> <span @mouseover="num=3" :class="num==3?'current':''">銀河新聞</span> </div> <div class="content"> <div class="list" :class="num==1?'active':''">國內新聞列表</div> <div class="list" :class="num==2?'active':''">國際新聞列表</div> <div class="list" :class="num==3?'active':''">銀河新聞列表</div> </div> </div> <script> // 實現一個js的特效時:關鍵是找出3個數據出來 // 1. 用戶操做的元素 // 2. 用戶觸發的事件 // 3. 事件觸發之後的效果是什麼? var vm = new Vue({ el:"#card", data:{ num:1, } }) </script> </body> </html>
控制指令[條件指令]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> <style> .box{ width: 50px; height: 50px; background: #000; } .box1{ background: #f66; } </style> </head> <body> <div id="app"> <div class="box" v-if="ok">v-if</div> <div class="box box1" v-else>v-else</div> <div class="box" v-show="ok">v-show</div> <hr> <div v-if="num%3==0">num是3的倍數</div> <div v-else-if="num%5==0">num是5的倍數</div> <div v-else-if="num%7==0">num是7的倍數</div> <div v-else>num都不是上面的倍數</div> </div> <script> var vm = new Vue({ el:"#app", data:{ ok:true, num: 3, } }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div id="app"> <table border="1" width="800px"> <tr> <th>序號</th> <th>ID</th> <th>姓名</th> <th>年齡</th> </tr> <tr v-for="student,key in student_list"> <td>{{key+1}}</td> <td>{{student.id}}</td> <td>{{student.name}}</td> <td>{{student.age}}</td> </tr> </table> </div> <script> var vm =new Vue({ el:'#app', data:{ student_list: [ {'id':1,'name':'小明1','age':13}, {'id':2,'name':'小明2','age':13}, {'id':3,'name':'小明3','age':13}, {'id':4,'name':'小明4','age':13}, {'id':5,'name':'小明1','age':13}, {'id':6,'name':'小明1','age':13}, ] } }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> <style> .orange{ background: orange; } </style> </head> <body> <div id="app"> <table border="1" width="800px"> <tr> <th>序號</th> <th>標題</th> <th>價格</th> </tr> <tr v-for="item,key in goods" :class="item.price>60?'orange':''"> <td>{{key+1}}</td> <td>{{item.name}}</td> <td>{{item.price}}</td> </tr> </table> </div> <script> var vm = new Vue({ el:"#app", data:{ goods:[ {"name":"python入門","price":150}, {"name":"python進階","price":100}, {"name":"python高級","price":75}, {"name":"python研究","price":60}, {"name":"python放棄","price":110}, ] } }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> <style> .win{ background: #aaa; width: 360px; height: 160px; padding: 20px; position: fixed; top: 150px; left: 0; right: 0; margin: auto; } </style> </head> <body> <div id="table"> <table border="1" width="600" align="center"> <tr> <td colspan="5"> <button @click="show_win=true">add</button> </td> </tr> <tr> <th>ID</th> <th>title</th> <th>number</th> <th>price</th> <th>operation</th> </tr> <tr v-for="goods,key in goods_list"> <td>{{goods.id}}</td> <td>{{goods.title}}</td> <td>{{goods.number}}</td> <td>{{goods.price}}</td> <td> <button @click="edit(key)">edit</button> <button @click="del(key)">del</button> </td> </tr> </table> <div class="win" v-if="show_win"> <label>title: <input type="text" v-model="title"></label><br><br> <label>number: <input type="text" v-model="number"></label><br><br> <label>price: <input type="text" v-model="price"></label><br><br> <button @click="save">肯定</button> <button @click="close">取消</button> </div> </div> <script> var vm = new Vue({ el:"#table", data:{ show_win: false, goods_list:[ {"id":1,"title":"代碼之髓","number":13,"price":78.5}, {"id":2,"title":"代碼之髓","number":23,"price":78.5}, {"id":3,"title":"代碼之髓","number":33,"price":78.5}, {"id":4,"title":"代碼之髓","number":43,"price":78.5}, ], id: 4, title:"", number:"", price:"", current:-1, //沒有編輯任何的內容 }, methods:{ save(){ // ID自增 this.id +=1; if(this.current==-1){ // 追加成員 this.goods_list.push({ "id": this.id, "title":this.title, "number":this.number, "price":this.price, }); }else{ // 編輯成員 this.goods_list[this.current].title=this.title; this.goods_list[this.current].number=this.number; this.goods_list[this.current].price=this.price; } this.close(); }, close(){ // 關閉窗口 this.show_win=false; // 重置編輯操做 this.current=-1; // 清空窗口中的數據 this.title=""; this.number=""; this.price=""; }, del(key){ console.log(key); this.goods_list.splice(key,1); }, edit(key){ this.current = key; this.title=this.goods_list[key].title; this.number=this.goods_list[key].number; this.price=this.goods_list[key].price; this.show_win=true; }, } }) </script> </body> </html>
過濾器,就是vue容許開發者自定義的文本格式化函數,可使用在兩個地方:輸出內容和操做數據中。
定義過濾器的方式有兩種。
全局過濾器, 經過Vue.filter("過濾器名稱",匿名函數)
<p>{{price|RMB}}</p>
Vue.filter("RMB", function(v){
return "¥"+v;
});
var vm = new Vue({
el:"#box",
data:{
price:30.5}
})
局部過濾器,直接把過濾器寫在當前vm對象中 <p>{{price|RMB}}</p> var vm = new Vue({ el:"#box", data:{ price:30.5}, filters:{ RMB(v){ return "¥"+v; }} })
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> <script src="js/filters.js"></script> </head> <body> <div id="box"> <p>{{price}}</p> <p>{{price2}}</p> </div> <script> // 當咱們須要針對data的數據盡心調整成另外一個變量,留做後面其餘地方進行運算使用時,可使用計算屬性得出一個新的變量 var vm = new Vue({ el:"#box", data:{ price:30.5 }, // 計算屬性 computed:{ price2:function(){ return this.price.toFixed(2); } } }) </script> </body> </html>
偵聽屬性,能夠幫助咱們偵聽data某個數據的變化,從而作相應的自定義操做。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> <script src="js/filters.js"></script> </head> <body> <div id="box"> 數量:<input type="text" v-model="num"> 單價:<input type="text" v-model="price"> 總價:{{total}} </div> <script> var vm = new Vue({ el:"#box", data:{ num: 0, price:30.5, total: 0 }, watch:{ num(newval,oldval){ // console.log("修改後num="+newval); // console.log("修改前num="+oldval); this.total = this.price * this.num; }, price(){ this.total = this.price * this.num; } } }) </script> </body> </html>
beforeCreate # vm對象還沒有建立,因此data中的數據是沒法操做 created # vm對象已經建立完成,可是尚未把數據和視圖模板進行綁定 beforeMount # 已經綁定了視圖,可是沒有更新視圖中的數據 mounted # 已經把data中的數據替換了模板視圖中對應的內容
beforeUpdate # 更新HTML模板的數據以前
updated # 更新HTML模板的數據以後
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.min.js"></script> <script> window.onload = function(){ var vm = new Vue({ el:"#app", data:{ num:0 }, beforeCreate:function(){ console.log("beforeCreate,vm對象還沒有建立,num="+ this.num); //undefined this.name=10; // 此時沒有this對象呢,因此設置的name無效,被在建立對象的時候被覆蓋爲0 }, created:function(){ console.log("created,vm對象建立完成,設置好了要控制的元素範圍,num="+this.num ); // 0 this.num = 20; }, beforeMount:function(){ console.log( this.$el.innerHTML ); // <p>{{num}}</p> console.log("beforeMount,vm對象還沒有把data數據顯示到頁面中,num="+this.num ); // 20 this.num = 30; }, mounted:function(){ console.log( this.$el.innerHTML ); // <p>30</p> console.log("mounted,vm對象已經把data數據顯示到頁面中,num="+this.num); // 30 }, beforeUpdate:function(){ // this.$el 就是咱們上面的el屬性了,$el表示當前vue.js所控制的元素#app console.log( this.$el.innerHTML ); // <p>30</p> console.log("beforeUpdate,vm對象還沒有把更新後的data數據顯示到頁面中,num="+this.num); // beforeUpdate----31 }, updated:function(){ console.log( this.$el.innerHTML ); // <p>31</p> console.log("updated,vm對象已經把過呢更新後的data數據顯示到頁面中,num=" + this.num ); // updated----31 }, }); } </script> </head> <body> <div id="app"> <p>{{num}}</p> <button @click="num++">按鈕</button> </div> </body> </html>
總結:
在vue使用的過程當中,若是要初始化操做,把初始化操做的代碼放在 mounted 中執行。
mounted階段就是在vm對象已經把data數據實現到頁面之後。通常頁面初始化使用。例如,用戶訪問頁面加載成功之後,就要執行的ajax請求。
另外一個就是created,這個階段就是在 vue對象建立之後,把ajax請求後端數據的代碼放進 created
事件,event,在js中表示用戶和瀏覽器之間進行的一次交互過程
事件在觸發時,就會有一個事件對象來記錄整個事件發生的過程和發生的位置
從事件發生位置由內及外,根據標籤之間父子嵌套關係,逐層往外傳播,讓父級元素觸發同類事件,這種事件的傳遞方式,就是 事件冒泡
事件冒泡有好,有壞。
好處就是能夠利用這種機制,實現事件委託
壞處就是當前元素的父級元素有同類事件,會隨着冒泡直接所有執行
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body onclick="alert('body')"> <div onclick="alert('div')"> <button>按鈕</button> </div> </body> </html>
局部變量 let 全局變量 var
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul id="list"> <li>111</li> <li>222</li> <li>3333</li> <li>4444</li> <li>1111</li> <li>1111</li> <li>1111</li> <li>1111</li> <li>1111</li> <li>1111</li> <li>1111</li> <li>1111</li> <li>1111</li> <li>1111</li> <li>1111</li> </ul> <script> var list = document.getElementById("list"); list.onclick = function(e){ console.log(this); // 事件綁定的對象 console.log(e.target); // 事件的觸發點 // console.log(e) let self = e.target; //局部變量 let 全局變量 var console.log(self.innerHTML); } </script> </body> </html>
e.stopPropagation();
e.cancelBubble = true;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="box"> <button id="btn">按鈕</button> </div> <script> var list = document.getElementById("box"); var btn = document.getElementById("btn"); list.onclick = function(){ alert("父元素"); }; btn.onclick = function(e){ alert("按鈕"); e.stopPropagation(); e.cancelBubble = true; } </script> </body> </html>
.stop 事件
.prevent a標籤事件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div id="box" @click="show2"> <button @click.stop="show">按鈕</button> <a href="" @click.prevent="show3">a連接</a> </div> <script> var vm = new Vue({ el:"#box", data:{}, methods:{ show(){ // alert("按鈕"); }, show2(){ // alert("父元素"); }, show3(){ console.log("一句話"); } } }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>todolist</title> <script src="js/vue.js"></script> <style type="text/css"> .list_con{ width:600px; margin:50px auto 0; } .inputtxt{ width:550px; height:30px; border:1px solid #ccc; padding:0px; text-indent:10px; } .inputbtn{ width:40px; height:32px; padding:0px; border:1px solid #ccc; } .list{ margin:0; padding:0; list-style:none; margin-top:20px; } .list li{ height:40px; line-height:40px; border-bottom:1px solid #ccc; } .list li span{ float:left; } .list li a{ float:right; text-decoration:none; margin:0 10px; } </style> </head> <body> <div class="list_con" id="app"> <h2>To do list</h2> <input type="text" name="" id="txt1" class="inputtxt"> <input type="button" name="" value="增長" id="btn1" class="inputbtn"> <ul id="list" class="list"> <!-- javascript:; # 阻止a標籤跳轉 --> <li v-for="item in todolist"> <span>{{item}}</span> <a href="javascript:;" class="up"> ↑ </a> <a href="javascript:;" class="down"> ↓ </a> <a href="javascript:;" class="del">刪除</a> </li> </ul> </div> <script> var vm = new Vue({ el:"#app", data:{ todolist:[ "學習html", "學習css", "學習javascript", ] } }); </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>todolist</title> <script src="js/vue.js"></script> <style type="text/css"> .list_con{ width:600px; margin:50px auto 0; } .inputtxt{ width:550px; height:30px; border:1px solid #ccc; padding:0px; text-indent:10px; } .inputbtn{ width:40px; height:32px; padding:0px; border:1px solid #ccc; } .list{ margin:0; padding:0; list-style:none; margin-top:20px; } .list li{ height:40px; line-height:40px; border-bottom:1px solid #ccc; } .list li span{ float:left; } .list li a{ float:right; text-decoration:none; margin:0 10px; } </style> </head> <body> <div class="list_con" id="app"> <h2>To do list</h2> <input type="text" v-model="text" id="txt1" class="inputtxt"> <input type="button" @click="add" value="增長" id="btn1" class="inputbtn"> <ul id="list" class="list"> <!-- javascript:; # 阻止a標籤跳轉 --> <li v-for="item in todolist"> <span>{{item}}</span> <a href="javascript:;" class="up"> ↑ </a> <a href="javascript:;" class="down"> ↓ </a> <a href="javascript:;" class="del">刪除</a> </li> </ul> </div> <script> var vm = new Vue({ el:"#app", data:{ text:"", todolist:[ "學習html", "學習css", "學習javascript", ] }, methods:{ add(){ this.todolist.push(this.text); this.text = ""; } } }); </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>todolist</title> <script src="js/vue.js"></script> <style type="text/css"> .list_con{ width:600px; margin:50px auto 0; } .inputtxt{ width:550px; height:30px; border:1px solid #ccc; padding:0px; text-indent:10px; } .inputbtn{ width:40px; height:32px; padding:0px; border:1px solid #ccc; } .list{ margin:0; padding:0; list-style:none; margin-top:20px; } .list li{ height:40px; line-height:40px; border-bottom:1px solid #ccc; } .list li span{ float:left; } .list li a{ float:right; text-decoration:none; margin:0 10px; } </style> </head> <body> <div class="list_con" id="app"> <h2>To do list</h2> <input type="text" v-model="text" id="txt1" class="inputtxt"> <input type="button" @click="add" value="增長" id="btn1" class="inputbtn"> <ul id="list" class="list"> <!-- javascript:; # 阻止a標籤跳轉 --> <li v-for="item,key in todolist"> <span>{{item}}</span> <a href="javascript:;" class="up"> ↑ </a> <a href="javascript:;" class="down"> ↓ </a> <a href="javascript:;" @click="del(key)" class="del">刪除</a> </li> </ul> </div> <script> var vm = new Vue({ el:"#app", data:{ text:"", todolist:[ "學習html", "學習css", "學習javascript", ] }, methods:{ add(){ this.todolist.push(this.text); this.text = ""; }, del(key){ this.todolist.splice(key,1); } } }); </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>todolist</title> <script src="js/vue.js"></script> <style type="text/css"> .list_con{ width:600px; margin:50px auto 0; } .inputtxt{ width:550px; height:30px; border:1px solid #ccc; padding:0px; text-indent:10px; } .inputbtn{ width:40px; height:32px; padding:0px; border:1px solid #ccc; } .list{ margin:0; padding:0; list-style:none; margin-top:20px; } .list li{ height:40px; line-height:40px; border-bottom:1px solid #ccc; } .list li span{ float:left; } .list li a{ float:right; text-decoration:none; margin:0 10px; } </style> </head> <body> <div class="list_con" id="app"> <h2>To do list</h2> <input type="text" v-model="text" id="txt1" class="inputtxt"> <input type="button" @click="add" value="增長" id="btn1" class="inputbtn"> <ul id="list" class="list"> <!-- javascript:; # 阻止a標籤跳轉 --> <li v-for="item,key in todolist"> <span>{{item}}</span> <a href="javascript:;" @click="up(key)" class="up"> ↑ </a> <a href="javascript:;" @click="down(key)" class="down"> ↓ </a> <a href="javascript:;" @click="del(key)" class="del">刪除</a> </li> </ul> </div> <script> var vm = new Vue({ el:"#app", data:{ text:"", todolist:[ "學習html", "學習css", "學習javascript", ] }, methods:{ add(){ this.todolist.push(this.text); this.text = ""; }, del(key){ // splice 萬能函數 this.todolist.splice(key,1); }, up(key){ // 向上移動 // splice(刪除的開始位置,刪除的成員個數, 替換的新數據) if(key===0){ return; } ret = this.todolist.splice(key,1)[0]; this.todolist.splice(key-1, 0, ret); }, down(key){ // 向下移動 ret = this.todolist.splice(key,1)[0]; this.todolist.splice(key+1, 0, ret); } } }); </script> </body> </html>
vue.js默認沒有提供ajax功能的。
因此使用vue的時候,通常都會使用axios的插件來實現ajax與後端服務器的數據交互。
注意,axios本質上就是javascript的ajax封裝,因此會被同源策略
下載地址:
https://unpkg.com/axios@0.18.0/dist/axios.js
https://unpkg.com/axios@0.18.0/dist/axios.min.js
axios提供發送請求的經常使用方法有兩個:axios.get() 和 axios.post() 。
增 post
刪 delete
改 put/patch put全部字段 /patch單一字段
// 發送get請求
// 參數1: 必填,字符串,請求的數據接口的url地址,例如請求地址:http://www.baidu.com?id=200
// 參數2:可選,json對象,要提供給數據接口的參數
// 參數3:可選,json對象,請求頭信息
axios.get('服務器的資源地址',{ // http://www.baidu.com
params:{
參數名:'參數值', // id: 200,
}
}).then(function (response) { // 請求成功之後的回調函數
console.log("請求成功");
console.log(response.data); // 獲取服務端提供的數據
}).catch(function (error) { // 請求失敗之後的回調函數
console.log("請求失敗");
console.log(error.response); // 獲取錯誤信息
});
// 發送post請求,參數和使用和axios.get()同樣。
// 參數1: 必填,字符串,請求的數據接口的url地址
// 參數2:必填,json對象,要提供給數據接口的參數,若是沒有參數,則必須使用{}
// 參數3:可選,json對象,請求頭信息
axios.post('服務器的資源地址',{
username: 'xiaoming',
password: '123456'
},{
responseData:"json",
})
.then(function (response) { // 請求成功之後的回調函數
console.log(response);
})
.catch(function (error) { // 請求失敗之後的回調函數
console.log(error);
});
// 匿名函數 var func = function(response){ // 函數代碼 }; // 箭頭函數 var func = (response)=>{ // 函數代碼 }
json是 JavaScript Object Notation 的首字母縮寫,單詞的意思是javascript對象表示法,這裏說的json指的是相似於javascript對象的一種數據格式。
json的做用:在不一樣的系統平臺,或不一樣編程語言之間傳遞數據。
JSON對象是字典,列表是數組
json數據對象相似於JavaScript中的對象,可是它的鍵對應的值裏面是沒有函數方法的,值能夠是普通變量,不支持undefined,值還能夠是數組或者json對象。// 原生的js的json對象 var obj = { age:10, sex: '女', work:function(){ return "好好學習", } }
// json數據的對象格式,json數據格式,是沒有方法的,只有屬性: { "name":"tom", "age":18 } // json數據的數組格式: ["tom",18,"programmer"]
複雜的json格式數據能夠包含對象和數組的寫法。
{ "name":"小明", "age":200, "is_delete": false, "fav":["code","eat","swim","read"], "son":{ "name":"小小明", "age":100, "lve":["code","eat"] } } // 數組結構也能夠做爲json傳輸數據。
json數據能夠保存在.json文件中,通常裏面就只有一個json對象。
1. json文件的後綴是.json 2. json文件通常保存一個單一的json數據 3. json數據的屬性不能是方法或者undefined,屬性值只能:數值[整數,小數,布爾值]、字符串、json和數組 4. json數據只使用雙引號、每個屬性成員之間使用逗號隔開,而且最後一個成員沒有逗號。 { "name":"小明", "age":200, "fav":["code","eat","swim","read"], "son":{ "name":"小小明", "age":100 } }
工具:postman能夠用於測試開發的數據接口。
javascript提供了一個JSON對象來操做json數據的數據轉換.
參數 | 返回值 | 描述 | |
---|---|---|---|
stringify | json對象 | 字符串 | json對象轉成字符串 |
parse | 字符串 | json對象 | 字符串格式的json數據轉成json對象 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>axios</title> <script src="js/vue.js"></script> <script src="js/axios.js"></script> </head> <body> <script> var data = { "name":"xiaopmiong", "age":13, "sex":true }; // 把json對象轉換成json字符串 json_str = JSON.stringify(data); console.log() // 把json字符串裝換成json對象 data_str = '{"name":"xiaopmiong","age":13,"sex":true}'; json_obj = JSON.parse(data_str); console.log(json_obj); </script> </body> </html>
數據接口,也叫api接口,表示後端提供
操做數據/功能的url地址給客戶端使用。
同時在工做中,大部分數據接口都不是手寫,而是經過函數庫/框架來生成。
ajax的使用必須與服務端程序配合使用,可是目前咱們先學習ajax的使用,因此暫時先不涉及到服務端python代碼的編寫。所以,咱們可使用別人寫好的數據接口進行調用。
jQuery將ajax封裝成了一個函數$.ajax(),咱們能夠直接用這個函數來執行ajax請求。
接口地址天氣接口http://wthrcdn.etouch.cn/weather_mini?city=城市名稱
音樂接口搜索http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=歌曲標題
音樂信息接口http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.song.play&songid=音樂ID
jQ版本:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/jquery-1.12.4.js"></script> <script> $(function(){ $("#btn").on("click",function(){ $.ajax({ // 後端程序的url地址 url: 'http://wthrcdn.etouch.cn/weather_mini', // 也可使用method,提交數據的方式,默認是'GET',經常使用的還有'POST' type: 'get', dataType: 'json', // 返回的數據格式,經常使用的有是'json','html',"jsonp" data:{ // 設置發送給服務器的數據,若是是get請求,也能夠寫在url地址的?後面 "city":'北京' } }) .done(function(resp) { // 請求成功之後的操做 console.log(resp); }) .fail(function(error) { // 請求失敗之後的操做 console.log(error); }); }); }) </script> </head> <body> <button id="btn">點擊獲取數據</button> </body> </html>
vue版本:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> <script src="js/axios.js"></script> </head> <body> <div id="app"> <input type="text" v-model="city"> <button @click="get_weather">點擊獲取天氣</button> </div> <script> let vm = new Vue({ el:"#app", data:{ city:"", }, methods:{ get_weather(){ // http://wthrcdn.etouch.cn/weather_mini?city=城市名稱 axios.get("http://wthrcdn.etouch.cn/weather_mini?city="+this.city) .then(response=>{ console.log(response); }).catch(error=>{ console.log(error.response) }); // 上面的參數寫法,也能夠是下面這種格式: // axios.get("http://wthrcdn.etouch.cn/weather_mini",{ // // get請求的附帶參數 // params:{ // "city":"廣州", // } // }).then(response=>{ // console.log(response.data); // 獲取接口數據 // }).catch(error=>{ // console.log(error.response); // 獲取錯誤信息 // }) } } }) </script> </body> </html>
ajax本質上仍是javascript,是運行在瀏覽器中的腳本語言,因此會被受到瀏覽器的同源策略所限制。
ajax跨域(跨源)方案:後端受權[CORS],jsonp,服務端代理
CORS是一個W3C標準,全稱是"跨域資源共享",它容許瀏覽器向跨源的後端服務器發出ajax請求,從而克服了AJAX只能同源使用的限制。
django的視圖
def post(request): response = new Response() response .headers["Access-Control-Allow-Origin"] = "http://localhost:63342" return response;
// 在響應行信息裏面設置如下內容: Access-Control-Allow-Origin: ajax所在的域名地址 Access-Control-Allow-Origin: www.oldboy.cn # 表示只容許www.oldboy.cn域名的客戶端的ajax跨域訪問 // * 表示任意源,表示容許任意源下的客戶端的ajax均可以訪問當前服務端信息 Access-Control-Allow-Origin: *
0. 同源策略:瀏覽器的一種保護用戶數據的一種安全機制。 瀏覽器會限制ajax不能跨源訪問其餘源的數據地址。 同源:判斷兩個通訊的地址之間,是否協議,域名[IP],端口一致。 ajax: http://127.0.0.1/index.html api數據接口: http://localhost/index 這兩個是同源麼?不是同源的。是否同源的判斷依據不會根據電腦來判斷,而是經過協議、域名、端口的字符串是否來判斷。 1. ajax默認狀況下會受到同源策略的影響,一旦受到影響會報錯誤以下: No 'Access-Control-Allow-Origin' header is present on the requested resource 2. 解決ajax只能同源訪問數據接口的方式: 1. CORS,跨域資源共享,在服務端的響應行中設置: Access-Control-Allow-Origin: 容許訪問的域名地址 2. jsonp 3. 是否服務端代理 思路:經過python來請求對應的服務器接口,獲取到數據之後,
組件(Component)是自定義封裝的功能。在前端開發過程當中,常常出現多個網頁的功能是重複的,並且不少不一樣的頁面之間,也存在一樣的功能。
而在網頁中實現一個功能,須要使用html定義功能的內容結構,使用css聲明功能的外觀樣式,還要使用js來定義功能的特效,所以就產生了把一個功能相關的[HTML、css和javascript]代碼封裝在一塊兒組成一個總體的代碼塊封裝模式,咱們稱之爲「組件」。
因此,組件就是一個html網頁中的功能,通常就是一個標籤,標籤中有本身的html內容結構,css樣式和js特效。
vue的組件有兩種:默認組件[全局組件] 和 單文件組件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div id="page"> <addnum></addnum> </div> <script> Vue.component("addnum",{ template:'<p>公共頭部<span @click="show">{{mes}}</span></p>', data:function () { return{ mes:"這是文本" } }, methods:{ show(){ alert(this.mes) } } }); var vm =new Vue({ el:'#page', data:{}, }) </script> </body> </html>
前面學習了普通組件之後,接下來咱們繼續學習單文件組件則須要提早先安裝準備一些組件開發工具。不然沒法使用和學習單文件組件。
通常狀況下,單文件組件,咱們運行在 自動化工具vue-CLI中,能夠幫咱們編譯單文件組件。因此咱們須要在系統中先搭建vue-CLI工具,
官網:
Vue CLI 須要 Node.js 8.9 或更高版本 (推薦 8.11.0+)。你可使用 nvm 或 nvm-windows在同一臺電腦中管理多個 Node 版本。
nvm工具的下載和安裝: https://www.jianshu.com/p/d0e0935b150a
https://www.jianshu.com/p/622ad36ee020
修改時區以及時間
查看時區
date -R
修改
tzselect
而後根據提示選擇 亞洲, 中國,北京
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
以後拷貝文件, 非root加上sudo
這樣再次查看就成功了
若是修改時間的話
sudo date -s MM/DD/YY //修改日期 sudo date -s hh:mm:ss //修改時間
最後更新 CMOS
sudo hwclock --systohc //很是重要,若是沒有這一步的話,後面時間仍是不許
安裝node
更新包管理器apt與apt-get
sudo apt update
sudo apt-get update
使用apt包管理器進行下載
sudo apt-get install nodejs # 下載nodejs sudo apt-get install npm #下載npm,它是nodejs的包管理器(nodejs package manager)
升級 npm
npm install npm -g # npm install -g npm # npm -g install npm
國內的npm不是很好用,使用cnpm代替npm的平常使用。
升級或安裝 cnpm
npm install cnpm -g
你可使用如下命令來查看全部全局安裝的模塊:
$ npm list -g
請先安裝git,安裝命令請參考下面
ubuntu系統
sudo apt-get install git
最新穩定版
$ cnpm install vue
命令行工具
Vue.js 提供一個官方命令行工具,可用於快速搭建大型單頁應用。
全局安裝 vue-cli
$ cnpm install --global vue-cli
使用 cnpm 安裝 webpack:
cnpm install webpack -g
建立一個基於 webpack 模板的新項目
$ vue init webpack my-project
num
注意:安裝nvm以前,要確保當前機子中不存在任何版本的node,若是有,則卸載掉
安裝命令:
sudo apt-get update sudo apt install curl curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash source ~/.bashrc
打開:https://github.com/coreybutler/nvm-windows/releases
安裝完成之後,先查看環境變量是否設置好了.
經常使用的nvm命令
nvm list # 列出目前在nvm裏面安裝的全部node版本 nvm install node版本號 # 安裝指定版本的node.js nvm uninstall node版本號 # 卸載指定版本的node.js nvm use node版本號 # 切換當前使用的node.js版本
若是使用nvm工具,則直接能夠不用本身手動下載,若是使用nvm下載安裝 node的npm比較慢的時候,能夠修改nvm的配置文件(在安裝根目錄下)
# settings.txt root: C:\tool\nvm [這裏的目錄地址是安裝nvm時本身設置的地址,要根據實際修改] path: C:\tool\nodejs arch: 64 proxy: none node_mirror: http://npm.taobao.org/mirrors/node/ npm_mirror: https://npm.taobao.org/mirrors/npm/
Node.js是一個新的後端(後臺)語言,它的語法和JavaScript相似,因此能夠說它是屬於前端的後端語言,後端語言和前端語言的區別:
運行環境:後端語言通常運行在服務器端,前端語言運行在客戶端的瀏覽器上
功能:後端語言能夠操做文件,能夠讀寫數據庫,前端語言不能操做文件,不能讀寫數據庫。
咱們通常安裝LTS(長線支持版本 Long-Time Support):
下載地址:https://nodejs.org/en/download/【上面已經安裝了nvm,那麼這裏不用手動安裝了】
node.js的版本有兩大分支:
官方發佈的node.js版本:0.xx.xx 這種版本號就是官方發佈的版本
Node.js若是安裝成功,能夠查看Node.js的版本,在終端輸入以下命令:
node -v
使用nvm的相關命令安裝node
# 查看官方提供的可安裝node版本 nvm ls-remote # 安裝執行版本的node,例如:nvm install v10.15.2 nvm install <version> # 卸載node版本,例如:nvm uninstall v10.15.2 nvm uninstall <version> # 查看已安裝的node列表 nvm install v10.15.2 # 切換node版本,例如:nvm use v10.15.2 nvm use <version> # 設置默認版本,若是沒有設置,則開機時默認node是沒有啓動的。 nvm alias default v10.15.2 # 查看當前使用的版本 nvm current
在安裝node.js完成後,在node.js中會同時幫咱們安裝一個npm包管理器npm。咱們能夠藉助npm命令來安裝node.js的包。這個工具至關於python的pip管理器。
npm install -g 包名 # 安裝模塊 -g表示全局安裝,若是沒有-g,則表示在當前項目安裝 npm list # 查看當前目錄下已安裝的node包 npm view 包名 engines # 查看包所依賴的Node的版本 npm outdated # 檢查包是否已通過時,命令會列出全部已過期的包 npm update 包名 # 更新node包 npm uninstall 包名 # 卸載node包 npm 命令 -h # 查看指定命令的幫助文檔
npm install -g vue-cli
使用vue自動化工具能夠快速搭建單頁應用項目目錄。
該工具爲現代化的前端開發工做流提供了開箱即用的構建配置。只需幾分鐘便可建立並啓動一個帶熱重載、保存時靜態檢查以及可用於生產環境的構建配置的項目:
// 生成一個基於 webpack 模板的新項目 vue init webpack 項目目錄名 例如: vue init webpack myproject // 啓動開發服務器 ctrl+c 中止服務 cd myproject npm run dev # 運行這個命令就能夠啓動node提供的測試http服務器
src 主開發目錄,要開發的單文件組件所有在這個目錄下的components目錄下
static 靜態資源目錄,全部的css,js文件放在這個文件夾
dist項目打包發佈文件夾,最後要上線單文件項目文件都在這個文件夾中[後面打包項目,讓項目中的vue組件通過編譯變成js 代碼之後,dist就出現了]
node_modules目錄是node的包目錄,
config是配置目錄,
build是項目打包時依賴的目錄
src/router 路由,後面須要咱們在使用Router路由的時候,本身聲明.
整個項目是一個主文件index.html,index.html中會引入src文件夾中的main.js,main.js中會導入頂級單文件組件App.vue,App.vue中會經過組件嵌套或者路由來引用components文件夾中的其餘單文件組件。
組件有兩種:普通組件、單文件組件
普通組件的缺點:
html代碼是做爲js的字符串進行編寫,因此組裝和開發的時候不易理解,並且沒有高亮效果。
普通組件用在小項目中很是合適,可是複雜的大項目中,若是把更多的組件放在html文件中,那麼維護成本就會變得很是昂貴。
將一個組件相關的html結構,css樣式,以及交互的JavaScript代碼從html文件中剝離出來,合成一個文件,這種文件就是單文件組件,至關於一個組件具備告終構、表現和行爲的完整功能,方便組件之間隨意組合以及組件的重用,這種文件的擴展名爲「.vue」,好比:"Home.vue"。
在組件中編輯三個標籤,編寫視圖、vm對象和css樣式代碼。
<template> <div id="Home"> <span @click="num--" class="sub">-</span> <input type="text" size="1" v-model="num"> <span @click="num++" class="add">+</span> </div> </template>
<script> export default {
// 組件名稱,未來提供給路由進行頁面跳轉的 name:"Home", data: function(){ return { num:0, } } } </script>
<style scoped>
.sub,.add{
border: 1px solid red;
padding: 4px 7px;
}
</style>
建立Homes.vue
<template> <div class="add_num"> <span @click="num++">+</span> <input type="text" size="2" v-model="num"> <span @click="num--">-</span> </div> </template> <script> export default{ name:"AddNum", data: function(){ return { num: 0, } } } </script> <style scoped> .add_num{ font-size: 32px; } </style>
在App.vue組件中調用上面的組件
<template> <div id="Home"> <span @click="num--" class="sub">-</span> <input type="text" size="1" v-model="num"> <span @click="num++" class="add">+</span> </div> </template> <script> export default { name:"Home", data: function(){ return { num:0, } } } </script> <style scoped> .sub,.add{ border: 1px solid red; padding: 4px 7px; } </style>
有時候開發vue項目時,頁面也能夠算是一個大組件,同時頁面也能夠分紅多個子組件.
由於,產生了父組件調用子組件的狀況.
例如,咱們能夠聲明一個組件,做爲父組件
// 組件中代碼必須寫在同一個標籤中 <template> <div id="menu"> <span>{{msg}}</span> <div>hello</div> </div> </template> <script> export default { name:"Menu", data: function(){ return { msg:"這是Menu組件裏面的菜單", } } } </script>
而後,在父組件中調用上面聲明的子組件。
最後,父組件被App.vue調用.就能夠看到頁面效果.
例如,咱們但願把父組件的數據傳遞給子組件.
能夠經過props屬性來進行數據傳遞.
傳遞數據三個步驟:
1. 在父組件中,調用子組件的組件標籤處,使用屬性值的方式往下傳遞數據
<Menu :mynum="num" title="home裏面寫的數據"/> # 上面表示在父組件調用Menu子組件的時候傳遞了2個數據: 若是要傳遞變量[變量能夠各類類型的數據],屬性名左邊必須加上冒號:,同時,屬性名是自定義的,會在子組件中使用。 若是要傳遞普通字符串數據,則不須要加上冒號:
2. 在子組件中接受上面父組件傳遞的數據,須要在vm組件對象中,使用props屬性類接受。
<script> export default { name:"Menu", props:["mynum","title"], data: function(){ return { msg:"這是Menu組件裏面的菜單", } } } </script> // 上面 props屬性中表示接受了兩個數據。
3. 在子組件中的template中使用父組件傳遞過來的數據.
<template> <div id="menu"> <span>{{msg}},{{title}}</span> <div>hello,{{mynum}}</div> </div> </template>
使用父組件傳遞數據給子組件時, 注意一下幾點:
傳遞數據是變量,則須要在屬性左邊添加冒號.
傳遞數據是變量,這種數據稱之爲"動態數據傳遞"
傳遞數據不是變量,這種數據稱之爲"靜態數據傳遞"
父組件中修改了數據,在子組件中會被同步修改,可是,子組件中的數據修改了,是否是影響到父組件中的數據.
這種狀況,在開發時,也被稱爲"單向數據流"
<template> <div> <p>Post的子組件</p> <h2>{{fnum}}</h2> <p>data={{data}}</p> <p>fnum={{fnum}}</p> <div><input type="text" v-model="fnum"></div> </div> </template> <script> export default { name: "PostSon", // 父組件傳遞數據給子組件: 1. 在父組件中調用子組件的組件名稱標籤上面聲明屬性和傳遞值,2. 在子組件中經過props進行接收 props:["data","fnum"], // 接受父組件中傳遞過來的數據 // 子組件傳遞數據給父組件[事件的方式進行傳遞]: watch:{ fnum(){ console.log(this.fnum); // this.$emit("父元素的自定義事件","要傳遞的數據"); // 經過this.$emit()方法,子組件能夠把數據傳遞給父組件 this.$emit("postparentdata",this.fnum); } } } </script> <style scoped> </style>
<template> <div> <h1>num={{num}}</h1> <Son data="我是付組件裏面的內容" :fnum="num" @postparentdata="getsondata"></Son> </div> </template>
3. 父組件中,聲明一個自定義方法,在事件被調用時,執行的。
<script> import Son from "./PostSon" export default { name: "Post", data(){ return { num: 100, } }, components:{ Son:Son, }, methods:{ getsondata(message){ console.log("父組件"+message); this.num = message; } } } </script>
默認狀況下,咱們的項目中並無對axios包的支持,因此咱們須要下載安裝。
npm install axios
接着在main.js文件中,導入axios並把axios對象 掛載到vue屬性中多爲一個子對象,這樣咱們才能在組件中使用。
// 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 axios from 'axios'; // 從node_modules目錄中導入包 Vue.config.productionTip = false Vue.prototype.$axios = axios; // 把對象掛載vue中 /* eslint-disable no-new */ new Vue({ el: '#app', components: { App }, template: '<App/>' });
<script> export default{ 。。。 methods:{ get_data:function(){ // 使用axios請求數據 this.$axios.get("http://wthrcdn.etouch.cn/weather_mini?city=深圳").then((response)=>{ console.log(response); }).catch(error=>{ console.log(error); }) } } } </script>
效果
使用的時候,由於本質上來講,咱們仍是原來的axios,因此也會收到同源策略的影響。