1.1 Vue簡介
1.1.1 官網
- 英文官網
- 中文官網
1.1.2 介紹與描述
- 動態構建用戶界面的 漸進式
JavaScript框架 - 作者:尤雨溪
1.1.3 Vue的特點
- 遵循
MVVM模式 - 編碼簡潔,體積小,運行效率高,適合移動/PC端開發
- 它本身只關注UI,也可以引入其它第三方庫開發專案
1.1.4 與其它JS框架的關聯
- 借鑒
Angular的模板和資料系結技術 - 借鑒
React的組件化和虛擬DOM技術
1.1.5 Vue 周邊庫
Vue CLI: 專案腳手架Vue ResourceAxiosVue Router: 路由Vuex: 狀態管理element-ui:基于Vue的UI組件庫(PC端)
......
1.2 初識 Vue
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>初識Vue</title>
<script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script>
</head>
<body>
<!--
初識Vue:
1.想讓 Vue作業,就必須創建一個 Vue實體,且要傳入一個配置物件;
2.root 容器里的代碼依然符合 html 規范,只不過混入了一些特殊的 Vue語法;
3.root 容器里的代碼被稱為【Vue模板】;
4.Vue 實體和容器是一一對應的;
5.真實開發中只有一個 Vue 實體,并且會配合著組件一起使用;
6.{{xxx}} 中的 xxx 要寫 js 運算式,且 xxx 可以自動讀取到 data 中的所有屬性;
7.一旦 data 中的資料發生改變,那么頁面中用到該資料的地方也會自動更新;
注意區分:js 運算式和 js 代碼(陳述句)
1.運算式:一個運算式會產生一個值,可以放在任何一個需要值的地方:
(1). a
(2). a+b
(3). demo(1)
(4). x === y ? 'a' : 'b'
2.js代碼(陳述句)
(1). if(){}
(2). for(){}
-->
<div id="root">
<h1>Hello {{name}}</h1>
</div>
<script>
// 阻止 Vue 在啟動時生成生產提示
// You are running Vue in development mode.
// Make sure to turn on production mode when deploying for production.
// See more tips at https://vuejs.org/guide/deployment.html
Vue.config.productionTip = false
// 創建 Vue 實體
new Vue({
// el 用于指定當前 Vue 實體為哪個容器服務,值通常為 css 選擇器字串
el: '#root',
// data 用于存盤資料,資料供 el 所指定的容器去使用
data: {
name: "張三"
},
})
</script>
</body>
</html>
1.3 模板語法
1.3.1 模板的理解
html 中包含了一些 js 語法代碼,語法分為兩種,分別為:
- 插值語法(雙大括號運算式)
- 指令(以v-開頭)
1.3.2 插值語法
- 功能:用于決議標簽體內容
1.3.3 指令語法
- 功能:決議標簽屬性、決議標簽體內容、系結事件
- 舉例:
v-bind:href='https://www.cnblogs.com/codechen8848/archive/2022/10/19/xxxx',xxxx會作為js運算式被決議 - 說明:
Vue中有有很多的指令,此處只是用v-bind舉個例子
1.3.4 示例代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue 模板語法</title>
<script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script>
</head>
<body>
<!--
Vue模板語法有2大類:
1.插值語法:
功能:用于決議標簽體內容,
寫法:{{xxx}},xxx 是 js 運算式,且可以直接讀取到 data 中的所有屬性,
2.指令語法:
功能:用于決議標簽(包括:標簽屬性、標簽體內容、系結事件.....),
舉例:v-bind:href="https://www.cnblogs.com/codechen8848/archive/2022/10/19/xxx" 或 簡寫為 :href="https://www.cnblogs.com/codechen8848/archive/2022/10/19/xxx",xxx同樣要寫js運算式,且可以直接讀取到 data 中的所有屬性,
備注:Vue 中有很多的指令,且形式都是:v-????,此處我們只是拿 v-bind 舉個例子,
-->
<div id="root">
<h1>插值語法</h1>
<h3>你好,{{name}}</h3>
<hr></hr>
<h1>指令語法</h1>
<a href="http://baidu.com">去百度</a>
<br/>
<a v-bind:href="https://www.cnblogs.com/codechen8848/archive/2022/10/19/school.url">去百度</a>
<br/>
<a :href="https://www.cnblogs.com/codechen8848/archive/2022/10/19/school.url">去百度</a>
</div>
<script>
// 阻止 Vue 在啟動時生成生產提示
Vue.config.productionTip = false
new Vue({
el: "#root",
data: {
name: "張三",
school: {
url: "http://baidu.com"
}
}
})
</script>
</body>
</html>
1.4 資料系結
1.4.1 單向資料系結
- 語法:
v-bind:href="https://www.cnblogs.com/codechen8848/archive/2022/10/19/xxx"或簡寫為:href - 特點:資料只能從
data流向頁面
1.4.2 雙向資料系結
- 語法:
v-model:value="https://www.cnblogs.com/codechen8848/archive/2022/10/19/xxx"或簡寫為v-model="xxx" - 特點:資料不僅能從
data流向頁面,還能從頁面流向data
1.4.3 示例代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>資料系結</title>
<script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script>
</head>
<body>
<!-- Vue中有2種資料系結的方式:
1.單向系結(v-bind):資料只能從 data 流向頁面,
2.雙向系結(v-model):資料不僅能從 data 流向頁面,還可以從頁面流向 data ,
備注:
1.雙向系結一般都應用在表單類元素上(如:input、select等)
2.v-model:value 可以簡寫為 v-model,因為 v-model默認收集的就是 value 值,
-->
<div id="root">
<!-- 單向系結 -->
<!-- 普通寫法 -->
單向系結普通寫法:<input type="text" v-bind:value="https://www.cnblogs.com/codechen8848/archive/2022/10/19/name"></input>
<br/>
<!-- 簡寫 -->
單向系結簡寫:<input type="text" :value="https://www.cnblogs.com/codechen8848/archive/2022/10/19/name"></input>
<hr></hr>
<!-- 雙向系結 -->
<!-- 普通寫法 -->
雙向系結普通寫法:<input type="text" v-model:value="https://www.cnblogs.com/codechen8848/archive/2022/10/19/name"></input>
<br/>
<!-- 簡寫 -->
雙向系結簡寫:<input type="text" v-model="name"></input>
<!-- 如下代碼是錯誤的,因為 v-model只能應用在表單類元素(輸入類元素)上 -->
<!-- <h2 v-model="name">: v-model is not supported on this element type.
If you are working with contenteditable, it's recommended to wrap a library dedicated for that purpose inside a custom component. -->
<h2 v-model:x="name"></h2>
</div>
<script>
// 組織 Vue 在啟動時生成生產提示
Vue.config.productionTip = false
new Vue({
el: "#root",
data: {
name: "張三"
}
})
</script>
</body>
</html>
1.5 MVVM模型
- M:模型(Model):對應
data中的資料 - V:視圖(View):模板
- VM:視圖模型(ViewModel):
Vue實體物件

1.6 事件處理
1.6.1 系結監聽
v-on:xxx="fun"@xxx="fun"@xxx="fun(引數)"- 默認事件形參:
event - 隱含屬性物件:
$event
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>事件的基本使用</title>
<script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script>
</head>
<body>
<!--
事件的基本使用:
1.使用 v-on:xxx 或 @xxx 系結事件,其中 xxx 是事件名;
2.事件的回呼需要配置在 vue 實體中的 methods 物件,最侄訓在 vm 實體上;
3.methods 中配置配置的函式,不要用箭頭函式,否則 this 就不是 vm 實體了;
4.methods 中配置的函式,都是被 vue 實體所管理的函式,this 的指向是 vm 或 組件實體物件;
5.@click="demo" 和 @click="demo($event)" 效果一致,但后者可以傳參
-->
<div id="root">
<h2>歡迎來到 {{name}} 學習</h2>
<button v-on:click = "showInfo01">點我去學習1</button>
<button v-on:click = "showInfo02">點我去學習2</button>
<button @click = "showInfo03">點我去學習3</button>
<button @click = "showInfo04(88)">點我去學習4</button>
<button @click = "showInfo05(88, $event)">點我去學習5</button>
</div>
<script>
// 阻止 vue 在啟動時生成生產提示
Vue.config.productionTip = false
new Vue({
el: "#root",
data() {
return {
name: "北京大學"
}
},
methods: {
showInfo01() {
alert("點我去學習1")
},
showInfo02(event) {
console.log(event);
},
showInfo03() {
alert("點我去學習3")
},
showInfo04(number) {
console.log(number);
alert("點我去學習4" + number)
},
showInfo05(number, event) {
console.log(number, event);
alert("點我去學習5")
},
},
})
</script>
</body>
</html>
1.6.2 事件修飾符
prevent: 阻止事件的默認行為event.preventDefault()stop: 停止事件冒泡event.stopPropagation()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>事件修飾符</title>
<script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script>
<style>
*{
margin-top: 20px;
}
.box1 {
height: 50px;
padding: 5px;
background-color: skyblue;
}
.box2 {
height: 50px;
padding: 5px;
background-color: orange;
}
.box3 {
height: 5px;
padding: 5px;
background-color: rebeccapurple;
}
.box4 {
height: 50px;
padding: 5px;
background-color: antiquewhite;
}
.list {
width: 200px;
height: 200px;
background-color: peru;
/* 在容器內生成滑動視窗 */
overflow: auto;
}
li {
height: 100px;
}
</style>
</head>
<body>
<!--
Vue中的事件修飾符:
1.prevent:阻止默認事件(常用);
2.stop:阻止事件冒泡(常用);
3.once:事件只觸發一次(常用);
4.capture:使用事件的捕獲模式;
5.self:只有event.target是當前操作的元素時才觸發事件;
6.passive:事件的默認行為立即執行,無需等待事件回呼執行完畢;
-->
<div id="root">
<!-- 1.阻止默認事件 -->
<!-- 彈窗點擊確認后會跳轉到百度 -->
<a href="https://www.baidu.com" @click="gotoBaidu">點我去百度</a><br/>
<!-- 彈窗點擊確認后不會跳轉到百度 -->
<a href="https://www.baidu.com" @click.prevent="gotoBaidu">點我去百度</a><br>
<!-- 2.stop:阻止事件冒泡 -->
<div class = "box1" @click="showInfo">
<button @click="showInfo">點我提示資訊</button>
</div>
<div class = "box1" @click="showInfo">
<button @click.stop="showInfo">點我提示資訊</button>
</div>
<!-- 3.once:事件只觸發一次 -->
<button @click.once="showInfo">點我提示資訊</button>
<!-- 4.capture:使用事件的捕獲模式 -->
<div @click.capture="showMessage(1)">
div01
<div @click.capture="showMessage(2)">
div02
</div>
</div>
<!-- 5.self:只有event.target是當前操作的元素時才觸發事件 -->
<div @click.self="showInfo">
<button @click="showInfo">點我提示資訊</button>
</div>
<!-- 6.passive:事件的默認行為立即執行,無需等待事件回呼執行完畢 -->\
<!--
@scroll、@wheel 滾輪滑動事件,兩者的區別:
1.scroll是頁面滾動條滾動會觸發的事件,而 wheel是滑鼠滾輪滾動會觸發的事件,
2,一旦滾動條到底部后,滑動滑鼠滾輪繼續滾動,wheel 就會一直觸發,而 scroll 不會觸發
-->
<ul @scroll="list">
<!-- <ul @wheel="list"> -->
<!-- <ul @wheel.passive="list"> -->
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<!-- 7.多個修飾符 -->
<div @click="showInfo">
<a href="https://www.baidu.com" @click="showInfo">點我去百度</a>
<a href="https://www.baidu.com" @click.prevent.stop="showInfo">點我去百度</a>
</div>
</div>
<script>
// 阻止 vue 在啟動時生成生產提示
Vue.config.productionTip = false
new Vue({
el: "#root",
data: {
},
methods: {
gotoBaidu() {
alert("點我去百度!")
},
showInfo() {
alert("hello world")
},
showMessage(message) {
console.log(message);
},
list() {
for(let i = 0; i < 10; i++) {
console.log("#");
}
console.log("累壞了");
}
},
})
</script>
</body>
</html>
1.6.3 按鍵修飾符
keycode: 操作的是某個keycode值的鍵keyName: 操作的某個按鍵名的鍵(少部分)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>鍵盤事件</title>
<script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script>
</head>
<body>
<!--
1.Vue中常用的按鍵別名:
回車 => enter
洗掉 => delete (捕獲“洗掉”和“退格”鍵)
退出 => esc
空格 => space
換行 => tab (特殊,必須配合keydown去使用)
上 => up
下 => down
左 => left
右 => right
2.Vue未提供別名的按鍵,可以使用按鍵原始的key值去系結,但注意要轉為kebab-case(短橫線命名)
3.系統修飾鍵(用法特殊):ctrl、alt、shift、meta
(1).配合keyup使用:按下修飾鍵的同時,再按下其他鍵,隨后釋放其他鍵,事件才被觸發,
(2).配合keydown使用:正常觸發事件,
4.也可以使用keyCode去指定具體的按鍵(不推薦)
5.Vue.config.keyCodes.自定義鍵名 = 鍵碼,可以去定制按鍵別名
-->
<div id="root">
<h3>歡迎來到{{name}}學習</h3>
<!-- @keydown、@keyup兩者的區別:前者是鍵盤按下事件,后者是鍵盤恢復事件 -->
<input placeholder="回車事件" @keydown="demo" ></input><br/>
<input placeholder="回車事件" @keydown.enter="demo"></input><br/>
<input placeholder="回車事件" @keydown.13="demo"></input><br/>
<input placeholder="回車事件" @keydown.huiche="demo"></input><br/>
<input placeholder="洗掉事件" @keydown.delete="demo"></input><br/>
<input placeholder="退出事件" @keydown.esc="demo"></input><br/>
<input placeholder="空格事件" @keydown.space="demo"></input><br/>
<input placeholder="換行事件" @keydown.tab="demo"></input><br/>
<input placeholder="上事件" @keydown.up="demo"></input><br/>
<input placeholder="下事件" @keydown.down="demo"></input><br/>
<input placeholder="左事件" @keydown.left="demo"></input><br/>
<input placeholder="右事件" @keydown.right="demo"></input><br/>
</div>
<script>
// 阻止 vue 在啟動時生成生產提示
Vue.config.productionTip = false
// 自定義鍵盤別名
Vue.config.keyCodes.huiche = 13
new Vue({
el: "#root",
data: {
name: "Blili"
},
methods: {
demo(event) {
// 輸出鍵值
console.log(event.key, event.keyCode);
console.log("hello world");
}
},
})
</script>
</body>
</html>
1.7 計算屬性與監視屬性
1.7.1 計算屬性 computed
-
要顯示的資料不存在,要通過計算得來,
-
在
computed物件中定義計算屬性, -
在頁面中使用插值語法來顯示計算的結果,
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>姓名案例-計算屬性實作</title> <script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script> </head> <body> <!-- 計算屬性: 1.定義:要用的屬性不存在,要通過已有屬性計算得來, 2.原理:底層借助了 Objcet.defineproperty 方法提供的 getter 和 setter , 3.get 函式什么時候執行? (1).初次讀取時會執行一次, (2).當依賴的資料發生改變時會被再次呼叫, 4.優勢:與 methods 實作相比,內部有快取機制(復用),效率更高,除錯方便, 5.備注: 1.計算屬性最侄訓出現在 vm 上,直接讀取使用即可, 2.如果計算屬性要被修改,那必須寫 set 函式去回應修改,且 set 中要引起計算時依賴的資料發生改變, --> <div id="root"> 姓:<input type="text" v-model="firstName"> <br/> 名:<input type="text" v-model="lastName"> <br/> <!-- 測驗:<input type="text" v-model="x"> <br/> --> 全名:<span>{{fullName}}</span> <br/> <!-- 全名:<span>{{fullName}}</span> <br/> 全名:<span>{{fullName}}</span> <br/> 全名:<span>{{fullName}}</span> --> </div> <script> // 阻止 vue 在啟動時生成生產提示 Vue.config.productionTip = false const vm = new Vue({ el: "#root", data: { firstName: "張", lastName: "三", }, computed: { fullName: { get() { //get 有什么作用?當有人讀取 fullName 時,get 就會被呼叫,且回傳值就作為 fullName 的值 //get 什么時候呼叫?1.初次讀取 fullName 時,2.所依賴的資料發生變化時, console.log("get 被呼叫了"); return this.firstName + " - " + this.lastName }, // set 什么時候被呼叫?fullName 被修改時 set(value) { console.log("set 被呼叫了"); const arr = value.split("-") this.firstName = arr[0] this.lastName = arr[1] } } } }); </script> </body> </html><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>姓名案例-計算屬性簡寫</title> <script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script> </head> <body> <div id="root"> 姓:<input type="text" v-model="firstName"> <br/> 名:<input type="text" v-model="lastName"> <br/> <!-- 測驗:<input type="text" v-model="x"> <br/> --> 全名:<span>{{fullName}}</span> <br/> </div> <script> // 阻止 vue 在啟動時生成生產提示 Vue.config.productionTip = false new Vue({ el: "#root", data: { firstName: "張", lastName: "三", }, computed: { // fullName:function() { // return this.firstName + " - " + this.lastName // }, fullName() { return this.firstName + " - " + this.lastName } } }) </script> </body> </html>
1.7.2 監視屬性 watch
-
通過通過
vm物件的$watch()或watch配置來監視指定的屬性 -
當屬性變化時,回呼函式自動呼叫,在函式內部進行計算
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>天氣案例-監視屬性</title> <script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script> </head> <body> <!-- 監視屬性 watch: 1.當被監視的屬性變化時, 回呼函式自動呼叫, 進行相關操作 2.監視的屬性必須存在,才能進行監視!! 3.監視的兩種寫法: (1).new Vue 時傳入 watch 配置 (2).通過 vm.$watch 監視 --> <div id="root"> <h2>今天天氣很{{info}}</h2> <button @click="changeWeather">切換天氣</button> </div> <script> // 阻止 vue 在啟動時生成生產提示 Vue.config.productionTip = false const vm = new Vue({ el: "#root", data: { isHot: true }, computed: { info() { return this.isHot ? "炎熱":"涼爽"; } }, methods: { changeWeather() { this.isHot = !this.isHot } }, watch: { // isHot: { // // 初始化的時候讓 handler 呼叫一下 // immediate: true, // // handler 什么時候被呼叫?當isHot值發生變化時 // handler(newValue, oldValue) { // console.log("isHot 值被修改了", newValue, oldValue); // } // }, // computed 中定義的屬性也能被監視 info: { handler(newValue, oldValue) { console.log("info值被修改了", newValue, oldValue); } } } }); // watch 屬性的另外一種寫法 vm.$watch("isHot", { // 初始化的時候讓 handler 呼叫一下 immediate: true, // handler 什么時候被呼叫?當isHot值發生變化時 handler(newValue, oldValue) { console.log("isHot 值被修改了", newValue, oldValue); } }) </script> </body> </html><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>天氣案例-深度監視</title> <script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script> </head> <body> <!-- 深度監視: (1).Vue 中的 watch 默認不監測物件內部值的改變(一層), (2).配置 deep:true 可以監測物件內部值改變(多層), 備注: (1).Vue 自身可以監測物件內部值的改變,但 Vue 提供的 watch 默認不可以! (2).使用 watch 時根據資料的具體結構,決定是否采用深度監視, --> <div id="root"> <h2>今天天氣很{{info}}</h2> <button @click="changeWeather">切換天氣</button> <hr/> <h3>x的值是:{{numbers.x}}</h3> <button @click="numbers.x ++">點我讓x + 1</button> <h3>y的值是:{{numbers.y}}</h3> <button @click="numbers.y ++">點我讓y + 1</button> <br/> <br/> <button @click="numbers = {x:666, y:888}">徹底替換掉numbers</button> </div> <script> // 阻止 vue 在啟動時生成生產提示 Vue.config.productionTip = false new Vue({ el: "#root", data: { isHot: true, numbers: { x: 100, y: 200 }, a: { b: { c: { d: "e" } } } }, computed: { info() { return this.isHot ? "炎熱":"涼爽"; } }, methods: { changeWeather() { this.isHot = !this.isHot } }, watch: { isHot: { // 初始化的時候讓 handler 呼叫一下 immediate: true, // handler 什么時候被呼叫?當isHot值發生變化時 handler(newValue, oldValue) { console.log("isHot 值被修改了", newValue, oldValue); } }, // computed 中定義的屬性也能被監視 info: { handler(newValue, oldValue) { console.log("info值被修改了", newValue, oldValue); } }, // 監視多級結構中某個屬性的變化 "numbers.x": { handler(newValue, oldValue) { console.log("numbers.x 值被修改了", newValue, oldValue); } }, //監視多級結構中所有屬性的變化 numbers: { deep: true, handler(newValue, oldValue) { console.log("numbers 值被修改了", newValue, oldValue); } } } }) </script> </body> </html><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>天氣案例-監視屬性-簡寫</title> <script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script> </head> <body> <div id="root"> <h2>今天天氣很{{info}}</h2> <button @click="changeWeather">切換天氣</button> </div> <script> // 阻止 vue 在啟動時生成生產提示 Vue.config.productionTip = false const vm = new Vue({ el: "#root", data: { isHot: true }, computed: { info() { return this.isHot ? "炎熱":"涼爽" } }, methods: { changeWeather() { this.isHot = !this.isHot } }, watch: { // 正常寫法 // isHot: { // // 在初始化時呼叫 handler 一次 // immediate: true, // handler(newValue, oldValue) { // console.log("isHot 值被修改了", newValue, oldValue); // } // }, // 簡寫 // 簡寫的缺點時不能寫屬性資訊 // isHot(newValue, oldValue) { // console.log("isHot 值被修改了", newValue, oldValue); // } }, }); // 正常寫法 // vm.$watch("isHot", { // // 初始化的時候讓 handler 呼叫一下 // immediate: true, // // handler 什么時候被呼叫?當isHot值發生變化時 // handler(newValue, oldValue) { // console.log("isHot 值被修改了", newValue, oldValue); // } // }) // 簡寫 vm.$watch("isHot", function(newValue, oldValue) { console.log("isHot 值被修改了", newValue, oldValue); }) </script> </body> </html>
1.8 class 與 style 系結
1.8.1 理解
- 在應用界面中,某個(些)元素的樣式是變化的
class/style系結就是專門用來實作動態樣式效果的技術
1.8.2 class 系結
:class='xxx'- 運算式是字串:
'classA' - 運算式是物件:
{classA:isA,classB:isB} - 運算式是陣列:
['classA','classB']
1.8.3 style 系結
:style="{color:activeColor,fontSize:fontSize+'px'}"- 其中
activeColor/fontSize是data屬性
1.8.4 示例代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>系結樣式</title>
<style>
.basic{
width: 400px;
height: 100px;
border: 1px solid black;
}
.happy{
border: 4px solid red;;
background-color: rgba(255, 255, 0, 0.644);
background: linear-gradient(30deg,yellow,pink,orange,yellow);
}
.sad{
border: 4px dashed rgb(2, 197, 2);
background-color: gray;
}
.normal{
background-color: skyblue;
}
.box1{
background-color: yellowgreen;
}
.box2{
font-size: 30px;
text-shadow:2px 2px 10px red;
}
.box3{
border-radius: 20px;
}
</style>
<script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script>
</head>
<body>
<!--
系結樣式:
1. class樣式
寫法: xxx可以是字串、物件、陣列,
字串寫法適用于:類名不確定,要動態獲取,
物件寫法適用于:要系結多個樣式,個數不確定,名字也不確定,
陣列寫法適用于:要系結多個樣式,個數確定,名字也確定,但不確定用不用,
2. style樣式
:style="{fontSize: xxx}"其中xxx是動態值,
:style="[a,b]"其中a、b是樣式物件,
3. 二者的區別:
:class 動態系結 class 的名稱,然后專門在 <style></style> 中去設定對應 class 的樣式
:style 動態系結 style 的效果,直接把 css 寫在里面
-->
<div id="root">
<!-- 系結 class 樣式(字串寫法),適用于:樣式的類名不確定,需要動態指定 -->
<div : @click="changeMood1">{{name}}</div> </br>
<!-- 系結 class 樣式(陣列寫法),適用于:要系結的樣式個數不確定、名字也不確定-->
<div :>{{name}}</div> </br>
<!-- 系結 class 樣式(物件寫法),適用于:要系結的樣式個數確定、名字也確定,但要動態決定用不用 -->
<div :>{{name}}</div> </br>
<!-- 系結 style 樣式(物件寫法) -->
<div :style="{fontSize: '40px', color: 'orange'}">{{name}}</div> </br>
<div :style="styleObj">{{name}}</div> </br>
<!-- 系結 style 樣式(陣列寫法) -->
<div :style="styleArr">{{name}}</div> </br>
</div>
<script>
// 阻止 vue 在啟動時生成生產提示
Vue.config.productionTip = false
new Vue({
el: "#root",
data: {
name: "Hello World",
mood: "happy",
moodArr: ["box1", "box2", "box3"],
moodObj: {
box1: true,
box2: false,
box3: true
},
styleObj: {
fontSize: "40px",
color: "red"
},
styleArr: [
{
fontSize: "40px",
color: "blue"
},
{
backgroundColor: "green"
}
]
},
methods: {
changeMood1() {
this.mood = "sad"
},
},
})
</script>
</body>
</html>
1.9 條件渲染
1.9.1 條件渲染指令
v-if與v-elsev-show
1.9.2 比較 v-if 與 v-show
- 如果需要頻繁切換
v-show較好 - 當條件不成立時,
v-if的所有子節點不會決議(專案中使用)
1.9.3 示例代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>條件渲染</title>
<script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script>
</head>
<body>
<!--
條件渲染:
1.v-if
寫法:
(1).v-if="運算式"
(2).v-else-if="運算式"
(3).v-else="運算式"
適用于:切換頻率較低的場景,
特點:不展示的 DOM 元素直接被移除,
注意:v-if 可以和: v-else-if、v-else 一起使用,但要求結構不能被“打斷”,
2.v-show
寫法:v-show="運算式"
適用于:切換頻率較高的場景,
特點:不展示的 DOM 元素未被移除,僅僅是使用樣式隱藏掉
3.備注:使用 v-if 時,元素可能無法獲取到,而使用 v-show 一定可以獲取到,
-->
<div id="root">
<!-- 使用 v-show 來做條件渲染 -->
<!-- <h2 style="display: none;"> 歡迎來到百度</h2> -->
<h2 v-show="false"> 歡迎來到{{name}}</h2>
<h2 v-show=" 1 === 1"> 歡迎來到{{name}}</h2>
<!-- 使用 v-if 來做條件渲染 -->
<h2 v-if="false"> 歡迎來到{{name}}</h2>
<h2 v-if="2 === 2"> 歡迎來到{{name}}</h2>
<!-- v-if與template的配合使用 -->
<template v-if="n === 1">
<h2>Angular</h2>
<h2>React</h2>
<h2>Vue</h2>
</template>
</div>
<script>
// 阻止 vue 在啟動時生成生產提示
Vue.config.productionTip = false
new Vue({
el: "#root",
data: {
name: "百度",
n: 1
}
})
</script>
</body>
</html>
1.10 串列渲染
1.10.1 串列顯示指令
- 遍歷陣列:
v-for/index - 遍歷物件:
v-for/key
1.10.2 示例代碼
-
基本串列
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>基本串列</title> <script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script> </head> <body> <!-- v-for指令: 1.用于展示串列資料 2.語法:v-for="(item, index) in xxx" :key="yyy" 3.可遍歷:陣列、物件、字串(用的很少)、指定次數(用的很少) --> <div id="root"> <!-- 遍歷陣列 --> <h2>遍歷陣列</h2> <!-- 用 id 作為 key --> <!-- <ul v-for="p in personList" :key = "p.id"> <li>{{p.name}} - {{p.age}}</li> </ul> --> <!-- 用索引 index 作為 key --> <ul v-for="(p, index) in personList" :key = "index"> <li>{{p.name}} - {{p.age}}</li> </ul> <hr/> <!-- 遍歷物件 --> <h2>遍歷物件</h2> <!-- 注意:key 在后面,value 在前面 --> <ul v-for="(v, k) in car" ::key="k"> <li>{{k}} - {{v}}</li> </ul> <hr/> <!-- 遍歷字串 --> <h2>遍歷字串</h2> <ul v-for="(char, index) in str" :key="index"> <ul>{{index}} - {{char}}</ul> </ul> <hr/> <!-- 遍歷指定次數 --> <h2>遍歷指定次數</h2> <ul v-for="i in 5"> <ul>{{i}}</ul> </ul> </div> <script> // 阻止 vue 在啟動時生成生產提示 Vue.config.productionTip = false new Vue({ el: "#root", data: { personList: [ {id: "001", name: "張三", age: 18}, {id: "002", name: "李四", age: 19}, {id: "003", name: "王五", age: 20}, ], car: { name: "奧迪 A8", price: "80萬", color: "黑色" }, str: "hello world" } }) </script> </body> </html> -
key的原理<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>key的原理</title> <script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script> </head> <body> <!-- 面試題:react、vue 中的 key 有什么作用?(key 的內部原理) 1. 虛擬 DOM 中 key 的作用: key 是虛擬 DOM 物件的標識,當資料發生變化時,Vue 會根據【新資料】生成【新的虛擬 DOM】, 隨后 Vue 進行【新虛擬 DOM】與【舊虛擬 DOM】的差異比較,比較規則如下: 2.對比規則: (1).舊虛擬 DOM 中找到了與新虛擬 DOM 相同的 key: ①.若虛擬 DOM 中內容沒變, 直接使用之前的真實 DOM! ②.若虛擬 DOM 中內容變了, 則生成新的真實 DOM,隨后替換掉頁面中之前的真實 DOM, (2).舊虛擬 DOM 中未找到與新虛擬 DOM 相同的 key 創建新的真實DOM,隨后渲染到到頁面, 3. 用 index 作為 key 可能會引發的問題: 1. 若對資料進行:逆序添加、逆序洗掉等破壞順序操作: 會產生沒有必要的真實 DOM 更新 ==> 界面效果沒問題, 但效率低, 2. 如果結構中還包含輸入類的 DOM: 會產生錯誤 DOM 更新 ==> 界面有問題, 4. 開發中如何選擇 key?: 1.最好使用每條資料的唯一標識作為 key, 比如 id、手機號、身份證號、學號等唯一值, 2.如果不存在對資料的逆序添加、逆序洗掉等破壞順序操作,僅用于渲染串列用于展示, 使用 index 作為 key 是沒有問題的, --> <div id="root"> <h2>遍歷陣列</h2> <button @click="add">在前面添加一個趙六</button> <!-- <ul v-for="(p, index) in personList" :key = "p.id"> --> <ul v-for="(p, index) in personList" :key = "index"> <li> {{p.name}} - {{p.age}} <input type="text"></input> </li> </ul> </div> <script> // 阻止 vue 在啟動時生成生產提示 Vue.config.productionTip = false new Vue({ el: "#root", data: { personList: [ {id: "001", name: "張三", age: 18}, {id: "002", name: "李四", age: 19}, {id: "003", name: "王五", age: 20}, ], }, methods: { add() { this.personList.unshift({ id: "004", name: "趙六", age: 38 }) } }, }) </script> </body> </html> -
串列過濾
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>串列過濾</title></title> <script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script> </head> <body> <div id="root"> <h2>遍歷陣列</h2> <input type="text" placeholder="輸入名字進行過濾" v-model="keyWord"></input> <ul v-for="(p, index) in filterPersonList" ::key="index"> <li>{{p.name}} - {{p.age}} - {{p.sex}}</li> </ul> </div> <script> // 阻止 vue 在啟動時生成生產提示 Vue.config.productionTip = false new Vue({ el: "#root", data: { keyWord:'', personList:[ {id:'001',name:'馬冬梅',age:19,sex:'女'}, {id:'002',name:'周冬雨',age:20,sex:'女'}, {id:'003',name:'周杰倫',age:21,sex:'男'}, {id:'004',name:'溫兆倫',age:22,sex:'男'} ], filterPersonList: [] }, // 用 comouted 實作 computed: { // filterPersonList() { // return this.personList.filter((item) => { // return item.name.indexOf(this.keyWord) > -1 // }) // } }, // 用 watch 實作 watch: { keyWord: { immediate: true, handler(val) { this.filterPersonList = this.personList.filter((item) => { return item.name.indexOf(this.keyWord) > -1 }) } } } }) </script> </body> </html> -
串列排序
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>串列排序</title> <script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script> </head> <body> <div id="root"> <h2>遍歷陣列</h2> <input type="text" placeholder="輸入名字進行過濾" v-model="keyWord"></input> <button @click="sortType = 1">升序排序</button></button> <button @click="sortType = 2">降序排列</button></button> <button @click="sortType = 0">原序排序</button></button> <ul v-for="(p, index) in filterPersonList" ::key="index"> <li>{{p.name}} - {{p.age}} - {{p.sex}}</li> </ul> </div> <script> // 阻止 vue 在啟動時生成生產提示 Vue.config.productionTip = false new Vue({ el: "#root", data: { keyWord:'', personList:[ {id:'001',name:'馬冬梅',age:19,sex:'女'}, {id:'002',name:'周冬雨',age:20,sex:'女'}, {id:'003',name:'周杰倫',age:21,sex:'男'}, {id:'004',name:'溫兆倫',age:22,sex:'男'} ], sortType: 1 }, // 用 comouted 實作 computed: { filterPersonList() { const arr = this.personList.filter((item) => { return item.name.indexOf(this.keyWord) > -1 }) if (this.sortType) { arr.sort((p1, p2) => { return this.sortType === 1 ? p1.age - p2.age : p2.age - p1.age }) } return arr } }, }) </script> </body> </html> -
更新時的一個問題
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>更新時的一個問題</title> <script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script> </head> <body> <div id="root"> <h2>人員串列</h2> <button @click="updateMa">更新馬冬梅的資訊</button> <ul> <li v-for="p in personList" :key="p.id"> {{p.name}} - {{p.age}} - {{p.sex}} </li> </ul> </div> <script> // 阻止 vue 在啟動時生成生產提示 Vue.config.productionTip = false new Vue({ el: "#root", data: { personList: [ {id:'001',name:'馬冬梅',age:19,sex:'女'}, {id:'002',name:'周冬雨',age:20,sex:'女'}, {id:'003',name:'周杰倫',age:21,sex:'男'}, {id:'004',name:'溫兆倫',age:22,sex:'男'} ] }, methods: { updateMa() { // 奏效的寫法 // this.personList[0].name = "馬老師" // this.personList[0].age = 50 // this.personList[0].sex = "男" // 不奏效的寫法 this.personList[0] = {name: "馬老師", age: 50, sex: "男"} } }, }) </script> </body> </html> -
Vue監測資料改變的原理-物件<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue 資料檢測改變的原理-物件</title> <script src="https://www.cnblogs.com/codechen8848/archive/2022/10/js/vue.js"></script> </head> <body> <div id="root"> <h2>學校名稱: {{name}}</h2> <h2>學校地址: {{address}}</h2> </div> <script> // 阻止 vue 在啟動時生成生產提示 Vue.config.productionTip = false new Vue({ el: "#root", data: { name: "北京大學", address: "北京", student: { name: "tom", age: { rAge: 40, sAge: 18 }, friends: [ {name: "jack", age: 38} ] } } }) </script> </body> </html> -
模擬一個資料監測
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>模擬一個資料檢測</title> </head> <body> <div id="root"> </div> <script> let data = https://www.cnblogs.com/codechen8848/archive/2022/10/19/{ name:"北京大學", address: "北京", student: { name: "tom", age: 18 } } // 創建一個監視的實體物件,用于監視 data 中屬性的變化 const obs = new Observer(data); // 準備一個 vm 實體物件 let vm = {} vm._data = https://www.cnblogs.com/codechen8848/archive/2022/10/19/data = obs function Observer(obj) { // 匯總物件中所有的屬性形成一個陣列 const keys = Object.keys(obj); // 遍歷 keys.forEach((k) => { Object.defineProperty(this, k, { get() { return obj[k] }, set(val) { obj[k] = val; } }) }) } // 存在的問題是對于深層次的屬性無法生成 get set 如:student 中的屬性 </script>
