1.關于vue
要理解記憶規則,可以到官網上去找
vue的兩種使用方式
- vue核心包開發
場景:局部模塊改造 - vue核心包 & vue插件 工程化開發
場景:整站開發
2.創建vue實例
構建用戶頁面->創建vue實例初始化渲染
學習階段用開發版本
3.插值表達式
- 使用的數據必須存在(data)
- 里面不能寫語句
- 不能在 標簽屬性 里面使用{{ }}插值
4.vue響應式
數據變化,視圖自動更新
data中的數據,是會被添加到實例上
- 訪問數據 實例.屬性名
- 修改數據 實例.屬性名 = 新值
修改數據-> vue監聽到數據修改-> 自動更新視圖DOM操作
5.vue指令v–html
動態的設置innerhtml
動態的解析標簽
代碼:
<body><div id="app"><div v-html="msg"></div></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {msg: `<h3>學前端~來黑馬!</h3>`}})</script>
</body>
6.v-show和v-if
均控制元素顯示隱藏
區別:
v-show底層原理:切換 css 的 display: none 來控制顯示隱藏
v-show=“false”
場景:頻繁切換顯示隱藏的場景v-if 底層原理:根據 判斷條件 控制元素的 創建 和 移除(條件渲染)
v-if=“false”
場景:不頻繁切換顯示隱藏的場景,eg:登錄
7.v-else和v-else-if
兩者均輔助v-if進行判斷渲染,緊挨著v-if使用
v-else,特別的,不能單獨使用
使用情況
- v-else,只有兩種,eg:性別
- v-else-if,兩個以上,eg:等級
<div id="app"><p v-if="gender === 1">性別:♂ 男</p><p v-else>性別:♀ 女</p><hr><p v-if="score >= 90">成績評定A:獎勵電腦一臺</p><p v-else-if="score >= 70">成績評定B:獎勵周末郊游</p><p v-else-if="score >= 60">成績評定C:獎勵零食禮包</p><p v-else>成績評定D:懲罰一周不能玩手機</p></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {gender: 2,score: 95}})</script>
8.v-on
注冊事件=添加監聽+提供處理邏輯
語法1:
簡寫
<button @click="count--">-</button>
詳寫
<button v-on:click="count++">+</button>
語法2:
v-on:事件名=”methods中的函數名“
必須先加this指向vue實例(app)才能拿到data里面的數據
<body><div id="app"><button @click="fn">切換顯示隱藏</button><h1 v-show="isShow">黑馬程序員</h1></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app4 = new Vue({el: '#app',data: {isShow: true},methods: {fn () {// 讓提供的所有methods中的函數,this都指向當前實例this.isShow = !this.isShow}}})</script>
</body>
9.v-on調用傳參
要用this
傳兩個,三個參數也是可以的
<body><div id="app"><div class="box"><h3>小黑自動售貨機</h3><button @click="buy(5)">可樂5元</button><button @click="buy(10)">咖啡10元</button><button @click="buy(8)">牛奶8元</button></div><p>銀行卡余額:{{ money }}元</p></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {money: 100},methods: { buy (price) {this.money -= price}}})</script>
</body>
10.v-bind
動態的設置html的標簽屬性
<img v-bind:src="imgUrl" v-bind:title="msg" alt="">
簡化版
<img :src="imgUrl" :title="msg" alt="">
11.波仔的學習之旅
代碼:
<body><div id="app"><button v-show="index > 0" @click="index--">上一頁</button><img :src="list[index]" alt=""><button v-show="index < list.length - 1" @click="index++">上一頁</button></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {index: 0,list: ['./imgs/11-00.gif','./imgs/11-01.gif','./imgs/11-02.gif','./imgs/11-03.gif','./imgs/11-04.png','./imgs/11-05.png',]}})</script>
</body>
12.v-for
基于數據循環,多次渲染整個元素,有對象,數組,數字
item是遍歷時的每一項
index是數組的下標
v-for="(item, index) in list"
例:
<li v-for="(item, index) in list">{{ item }} - {{ index }}</li>不用index時<li v-for="item in list">{{ item }}</li>
v-for 里面的key
給列表添加唯一的標識,便于vue進行列表項的正確排序復用
注意:
- key的值只能是字符串或者是數字類型
- key的值必須唯一
- 推薦使用id作為key,不推薦使用index(會變化,不對應)
13.小黑的書架
** filter: 根據條件,保留滿足條件的對應項,得到一個新數組。**
this.bookList = this.bookList.filter(item => item.id !=id)
<body><div id="app"><h3>小黑的書架</h3><ul><li v-for="(item,index) in booksList"><span>{{ item.name }}</span><span>{{ item.author }}</span><button @click="del(item.id)">刪除</button></li></ul></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {booksList: [{ id: 1, name: '《紅樓夢》', author: '曹雪芹' },{ id: 2, name: '《西游記》', author: '吳承恩' },{ id: 3, name: '《水滸傳》', author: '施耐庵' },{ id: 4, name: '《三國演義》', author: '羅貫中' }]},methods: {del(id) {this.booksList = this.booksList.filter(item => item.id !=id)}}})</script>
</body>
14.v-model
給表單元素使用
v-model 可以讓數據和視圖,形成雙向數據綁定
(1) 數據變化,視圖自動更新
(2) 視圖變化,數據自動更新
可以快速[獲取]或[設置]表單元素的內容
v-model的綁定內容寫在data里面
<body><div id="app">賬戶:<input type="text" v-model="username"> <br><br>密碼:<input type="password" v-model="password"> <br><br><button @click="login">登錄</button><button @click="reset">重置</button></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {username: ' ' ,password: ' '},methods: {login () {console.log(this.username, this.password)},reset () {this.username = ' 'this.password = ' '}}})</script>
</body>
15.小黑記事本
<body><!-- 主體區域 -->
<section id="app"><!-- 輸入框 --><header class="header"><h1>小黑記事本</h1><input v-model="todoName" placeholder="請輸入任務" class="new-todo" /><button class="add" @click="add()">添加任務</button></header><!-- 列表區域 --><section class="main"><ul class="todo-list"><li class="todo" v-for="(item, index) in list" :key="item.id"><div class="view"><span class="index">{{ index + 1 }}.</span> <label>{{ item.name }}</label><button @click="del(item.id)" class="destroy"></button></div></li></ul></section><!-- 統計和清空 -> 如果沒有任務底部需清空--><footer class="footer" v-show="list.length > 0"><!-- 統計 --><span class="todo-count">合 計:<strong> {{ list.length }} </strong></span><!-- 清空 --><button @click="clear()" class="clear-completed">清空任務</button></footer>
</section><!-- 底部 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>// 添加功能//用v-model//點擊按鈕,進行新增,往數組最前面加 unshiftconst app = new Vue({el: '#app',data: {todoName: '',list: [{ id: 1, name: '跑步一公里' },{ id: 3, name: '游泳100米' },]},methods: {del (id) {// console.log(id) => filter 保留所有不等于該 id 的項this.list = this.list.filter(item => item.id !== id)},add() {if(this.todoName.trim === ''){alert('請輸入任務名稱')return}this.list.unshift({id: +new Date(),name: this.todoName})this.todoName = ''},clear() {this.list = []}}})</script>
</body>
16.指令修飾符
通過"."指明一些指令 后綴,不同后綴封裝不同的處理操作 -> 簡化代碼
- 按鍵修飾符
@keyup.enter="fn" 鍵盤回車監聽
- v-model修飾符
v-model.trim="username" 去除首尾空格
v-model.number="age" 轉數字
- 事件修飾符
@click.stop="sonFn" 阻止冒泡
@click.prevent 阻止默認行為
17.v-bind對于樣式控制的增強
語法:
:class=“對象/數組”
- 對象:鍵就是類名,值是布爾值,true則有類,反之
<div class="box" :class="{ pink: true, big: true }">黑馬程序員</div>
使用場景:一個類名,來回切換
2. 數組:數組中所有的類,都會添加到盒子上,本質就是class列表
<div class="box" :class="['pink', 'big']">黑馬程序員</div>
使用場景:批量添加或刪除類
操作style
語法:
值必須用引號引起來!
行內樣式強大的是對單個屬性的控制
<div class="box" :style="{ width: '400px', height: '400px', backgroundColor: 'green' }"></div>
案例:
<body><div id="app"><!-- 外層盒子底色 (黑色) --><div class="progress"><!-- 內層盒子 - 進度(藍色) --><div class="inner" :style="{ width: percent + '%' }"><span>{{ percent }}%</span></div></div><button @click="percent = 25">設置25%</button><button @click="percent = 50">設置50%</button><button @click="percent = 75">設置75%</button><button @click="percent = 100">設置100%</button></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {percent: 30}})</script>
</body>
18.京東秒殺tab導航高亮
<body><div id="app"><ul><li v-for="(item,index) in list" :key="item.id" @click="activeIndex = index"><a :class="{active: index === activeIndex}" href="#">{{ item.name }}</a></li></ul></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {activeIndex: 2, // 記錄高亮list: [{ id: 1, name: '京東秒殺' },{ id: 2, name: '每日特價' },{ id: 3, name: '品類秒殺' }]}})</script>
</body>
19.v-model應用于其他表單元素
常見的表單元素
- 輸入框 input:text ->value
- 文本域textarea ->value
- 復選框 input:checkbox ->checked
- 單選框 input:radio ->checked
- 下拉菜單 select ->value
name: 給單選框加上 name 屬性 可以分組 → 同一組互相會互斥
value: 給單選框加上 value 屬性,用于提交給后臺的數據
結合 Vue 使用 → v-model
性別: <input v-model="gender" type="radio" name="gender" value="1">男<input v-model="gender" type="radio" name="gender" value="2">女<br><br>
option 需要設置 value 值,提交給后臺
select 的 value 值,關聯了選中的 option 的 value 值
結合 Vue 使用 → v-model
所在城市:<select v-model="cityId"><option value="101">北京</option><option value="102">上海</option><option value="103">成都</option><option value="104">南京</option></select><br><br>自我描述:<textarea v-model="desc"></textarea> <button>立即注冊</button></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {username: ' ',isSingle: false,gender: "2",cityId: '102',desc: " "}})</script>
20.計算屬性
放在與data并列的computed里
基于現有的數據,編寫求值邏輯
在computed配置項里,一個計算屬性對應一個函數
使用:{{ 計算屬性名 }}
一定要return
computed: {//計算屬性名 () {// 基于現有的數據,編寫求值邏輯return 結果
}
求和用reduce
需求:
對 this.list 數組里面的 num 進行求和 → reduce
//0 是求和的起始值
let total = this.list.reduce((sum, item) => sum + item.num,0)
return total
21.computed計算屬性 VS methods 方法
computed計算屬性
封裝數據處理,求結果
特別的:有緩存的,一旦計算出來結果,就會立刻緩存,下一次讀取 → 直接讀緩存就行 → 性能特別高
作為屬性直接使用,this.計算屬性{{ 計算屬性 }}methods 方法
給實例提供方法,調用以處理業務邏輯
作為方法,需要調用,this.方法名() {{ 方法名() }} @事件名=“方法名”
22.計算屬性完整寫法
computed: {// 完整寫法 → 獲取 + 設置fullName: {get () {一段代碼邏輯(計算邏輯)return 結果},set (修改的值) {一段代碼邏輯(修改邏輯)}}}
改名卡案例
<body><div id="app">姓:<input type="text" v-model="firstName"> +名:<input type="text" v-model="lastName"> =<span>{{ fullName }}</span><br><br><button @click="changeName">改名卡</button></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {firstName: '劉',lastName: '備',},methods: {changeName () {this.fullName = '黃忠'}},computed: {// 簡寫 → 獲取,沒有配置設置的邏輯// fullName () {// return this.firstName + this.lastName// }// 完整寫法 → 獲取 + 設置fullName: {// (1) 當fullName計算屬性,被獲取求值時,執行get(有緩存,優先讀緩存)// 會將返回值作為,求值的結果get () {return this.firstName + this.lastName},// (2) 當fullName計算屬性,被修改賦值時,執行set// 修改的值,傳遞給set方法的形參set (value) {// console.log(value.slice(0, 1)) // console.log(value.slice(1)) this.firstName = value.slice(0, 1)this.lastName = value.slice(1)}}}})</script>
</body>
23.成績案例
<body><div id="app" class="score-case"><div class="table"><table><thead><tr><th>編號</th><th>科目</th><th>成績</th><th>操作</th></tr></thead><tbody v-if="list.length > 0"><tr v-for="(item,index) in list" :key="item.id"><td>{{ index + 1 }}</td><td>{{item.subject}}</td><td :class="{red: item.score < 60 }">{{item.score}}</td><td><a @click.prevent="del(item.id)" href="#">刪除</a></td></tr></tbody><tbody v-else><tr><td colspan="5"><span class="none">暫無數據</span></td></tr></tbody><tfoot><tr><td colspan="5"><span>總分:{{ totalCount }}</span><span style="margin-left: 50px">平均分:{{ averageCount }}</span></td></tr></tfoot></table></div><div class="form"><div class="form-item"><div class="label">科目:</div><div class="input"><inputtype="text"placeholder="請輸入科目"v-model.trim="subject"/></div></div><div class="form-item"><div class="label">分數:</div><div class="input"><inputtype="text"placeholder="請輸入分數"v-model.number="score"/></div></div><div class="form-item"><div class="label"></div><div class="input"><button @click="add" class="submit" >添加</button></div></div></div></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const app = new Vue({el: '#app',data: {list: [{ id: 1, subject: '語文', score: 20 },{ id: 7, subject: '數學', score: 99 },{ id: 12, subject: '英語', score: 70 },],subject: '',score: ''},computed:{totalCount() {return this.list.reduce((sum,item) => sum + item.score,0)},averageCount () {if (this.list.length === 0) {return 0}//toFixed(2)保留兩位小數return (this.totalCount / this.list.length).toFixed(2)}},methods: {del(id) {this.list = this.list.filter(item => item.id != id)},add() {if (!this.subject) {alert('請輸入科目名稱')return}if(typeof this.score !== 'number') {alert('請輸入正確的成績')return}//在開頭插入元素 unshiftthis.list.unshift({id: +new Date(),subject: this.subject,score: this.score})this.subject = ''this.score = ''}}})</script></body>
24.watch偵聽器(監視器)
可持久化到本地
監視數據變化,執行業務邏輯或異步操作
- 簡單寫法:簡單類型數據,直接監視
- 完整寫法:添加額外配置項
簡單寫法
** ‘obj.words’ ,對象里面的子屬性,方法名一定要加引號**
若是直接屬性名,則不用加引號
const app = new Vue({el: '#app',data: {// words: ''obj: {words: ''}},// 具體講解:(1) watch語法 (2) 具體業務實現watch: {// 該方法會在數據變化時調用執行// newValue新值, oldValue老值(一般不用)// words (newValue) {// console.log('變化了', newValue)// }'obj.words' (newValue) {console.log('變化了', newValue)}}})
加上防抖效果,防止多次觸發
'obj.words' (newValue) {// console.log('變化了', newValue)// 防抖: 延遲執行 → 干啥事先等一等,延遲一會,一段時間內沒有再次觸發,才執行clearTimeout(this.timer)this.timer = setTimeout(async () => {const res = await axios({url: 'https://applet-base-api-t.itheima.net/api/translate',params: {words: newValue}})this.result = res.data.dataconsole.log(res.data.data)}, 300)}
完整寫法
deep: true, // 深度監視
immediate: true, // 立刻執行,一進入頁面handler就立刻執行一次
handler (newValue) {clearTimeout(this.timer)this.timer = setTimeout(async () => {const res = await axios({url: 'https://applet-base-api-t.itheima.net/api/translate',params: newValue})this.result = res.data.dataconsole.log(res.data.data)}, 300)}
25.水果購物車
!!!!!!!!!!!!!!!!!!!!!!!!!!
計算屬性的完整寫法 isAll: { get() {}, set() {} } 全名用冒號
watch監聽器 里的監聽的對象要用冒號 watch : { list: {} }
computed計算屬性 、methods 方法、watch監聽一律用冒號
<body><div class="app-container" id="app"><!-- 頂部banner --><div class="banner-box"><img src="http://autumnfish.cn/static/fruit.jpg" alt="" /></div><!-- 面包屑 --><div class="breadcrumb"><span>🏠</span>/<span>購物車</span></div><!-- 購物車主體 --><div class="main" v-if="fruitList.length > 0"><div class="table"><!-- 頭部 --><div class="thead"><div class="tr"><div class="th">選中</div><div class="th th-pic">圖片</div><div class="th">單價</div><div class="th num-th">個數</div><div class="th">小計</div><div class="th">操作</div></div></div><!-- 身體 --><div class="tbody"><div class="tr" v-for="(item,index) in fruitList" :key="item.id" :class="{active: item.isChecked}"><div class="td"><input type="checkbox" v-model="item.isChecked" /></div><div class="td"><img :src="item.icon" alt="" /></div><div class="td">{{ item.price }}</div><div class="td"><div class="my-input-number"><button class="decrease" :disabled="item.num <= 1" @click="sub(item.id)"> - </button><span class="my-input__inner">{{ item.num }}</span><button class="increase" @click="add(item.id)"> + </button></div></div><div class="td">{{ item.price*item.num }}</div><div class="td"><button @click="del(item.id)">刪除</button></div></div></div></div><!-- 底部 --><div class="bottom"><!-- 全選 --><label class="check-all"><input type="checkbox" v-model="isAll"/>全選</label><div class="right-box"><!-- 所有商品總價 --><span class="price-box">總價 : ¥ <span class="price">{{ totalPrice }}</span></span><!-- 結算按鈕 --><button class="pay">結算( {{ totalCount }} )</button></div></div></div><!-- 空車 --><div class="empty" v-else>🛒空空如也</div></div><script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script><script>const defaultArr = [{id: 1,icon: 'http://autumnfish.cn/static/火龍果.png',isChecked: true,num: 2,price: 6,},{id: 2,icon: 'http://autumnfish.cn/static/荔枝.png',isChecked: false,num: 7,price: 20,},{id: 3,icon: 'http://autumnfish.cn/static/榴蓮.png',isChecked: false,num: 3,price: 40,},{id: 4,icon: 'http://autumnfish.cn/static/鴨梨.png',isChecked: true,num: 10,price: 3,},{id: 5,icon: 'http://autumnfish.cn/static/櫻桃.png',isChecked: false,num: 20,price: 34,},]const app = new Vue({el: '#app',data: {// 水果列表fruitList: JSON.parse(localStorage.setItem('list') || defaultArr),},computed: {//完整寫法= get + setisAll : {get() {//必須所有的小選框都選中,全選按鈕才選中 => everyreturn this.fruitList.every(item => item.isChecked)},set(value) {//拿到的value值是true或false//同步狀態是賦值,=this.fruitList.forEach(item => item.isChecked = true)}},//統計選中的總數 reducetotalCount(){return this.fruitList.reduce((sum,item) => {if(item.isChecked){return sum + item.num}else{return sum}} ,0)},//統計選中的總價totalPrice() {return this.fruitList.reduce((sum,item) => {if(item.isChecked){return (sum + item.num) * item.price}else{return sum}} ,0)}},methods: {del(id) {this.fruitList = this.fruitList.filter(item => item.id !==id)},add(id) {//findconst fruit = this.fruitList.find(item => item.id === id)fruit.num++},sub(id) {const fruit = this.fruitList.find(item => item.id === id)fruit.num--}},//持久化到本地就是要用到監聽watch : {fruitList: {deep: true,handler(newValue) {//將變化的newValue存入本地(轉JSON)localStorage.setItem('list',JSON.stringify(newValue))}}}})</script></body>
26.vue生命周期和生命周期的四個鉤子
vue生命周期 :一個vue實例從創建到銷毀的整個過程
創建 響應式數據
掛載 渲染模板
更新 數據修改,更新視圖
銷毀 銷毀實例
before Create
created 發送初始化渲染請求 常用
before Mount
mounted 操作DOM 常用
before Update
updated
before Destroy 釋放vue以外的資源(清楚定時器,延時器…)常用
destroyed
27.created應用,mounted應用
created鉤子與data并列
created:響應式數據準備好了,可以發送初始化渲染請求
- created應用
async created () {// 1. 發送請求獲取數據const res = await axios.get('http://hmajax.itheima.net/api/news')// 2. 更新到 list 中,用于頁面渲染 v-forthis.list = res.data.data}
- mounted應用
// 核心思路:// 1. 等input框渲染出來 mounted 鉤子// 2. 讓input框獲取焦點 inp.focus()mounted () {document.querySelector('#inp').focus()}})
28.小黑記賬清單
功能需求:
1. 基本渲染
(1) 立刻發送請求獲取數據 created
(2) 拿到數據,存到data的響應式數據中
(3) 結合數據,進行渲染 v-for
(4) 消費統計 => 計算屬性
2. 添加功能
(1) 收集表單數據 v-model
(2) 給添加按鈕注冊點擊事件,發送添加請求
(3) 需要重新渲染
3. 刪除功能
(1) 注冊點擊事件,傳參傳 id
(2) 根據 id 發送刪除請求
(3) 需要重新渲染
4. 餅圖渲染
(1) 初始化一個餅圖 echarts.init(dom) mounted鉤子實現
(2) 根據數據實時更新餅圖 echarts.setOption({ … })