一篇文章帶你吃透Vue生命周期(結(jié)合案例通俗易懂)
1. vue生命周期
1.0_人的-生命周期
一組件從 創(chuàng)建 到 銷毀 的整個(gè)過程就是生命周期
Vue_生命周期
1.1_鉤子函數(shù)
目標(biāo): Vue 框架內(nèi)置函數(shù),隨著組件的生命周期階段,自動(dòng)執(zhí)行
作用: 特定的時(shí)間點(diǎn),執(zhí)行特定的操作
場景: 組件創(chuàng)建完畢后,可以在created 生命周期函數(shù)中發(fā)起Ajax 請求,從而初始化 data 數(shù)據(jù)
分類: 4大階段8個(gè)方法
- 初始化
- 掛載
- 更新
- 銷毀
階段 | 方法名 | 方法名 |
---|---|---|
初始化 | beforeCreate | created |
掛載 | beforeMount | mounted |
更新 | beforeUpdate | updated |
銷毀 | beforeDestroy | destroyed |
下圖展示了實(shí)例的生命周期。你不需要立馬弄明白所有的東西,不過隨著你的不斷學(xué)習(xí)和使用,它的參考價(jià)值會(huì)越來越高。
1.2_初始化階段
目標(biāo): 掌握初始化階段2個(gè)鉤子函數(shù)作用和執(zhí)行時(shí)機(jī)
含義講解:
1.new Vue() – Vue實(shí)例化(組件也是一個(gè)小的Vue實(shí)例)
2.Init Events & Lifecycle – 初始化事件和生命周期函數(shù)
3.beforeCreate – 生命周期鉤子函數(shù)被執(zhí)行
4.Init injections&reactivity – Vue內(nèi)部添加data和methods等
5.created – 生命周期鉤子函數(shù)被執(zhí)行, 實(shí)例創(chuàng)建
6.接下來是編譯模板階段 –開始分析
7.Has el option? – 是否有el選項(xiàng) – 檢查要掛到哪里
? 沒有. 調(diào)用$mount()方法
? 有, 繼續(xù)檢查template選項(xiàng)
components/Life.vue - 創(chuàng)建一個(gè)文件
<script> export default { data(){ return { msg: "hello, Vue" } }, // 一. 初始化 // new Vue()以后, vue內(nèi)部給實(shí)例對象添加了一些屬性和方法, data和methods初始化"之前" beforeCreate(){ console.log("beforeCreate -- 執(zhí)行"); console.log(this.msg); // undefined }, // data和methods初始化以后 // 場景: 網(wǎng)絡(luò)請求, 注冊全局事件 created(){ console.log("created -- 執(zhí)行"); console.log(this.msg); // hello, Vue this.timer = setInterval(() => { console.log("哈哈哈"); }, 1000) } } </script>
App.vue - 引入使用
<template> <div> <h1>1. 生命周期</h1> <Life></Life> </div> </template> <script> import Life from './components/Life' export default { components: { Life } } </script>
1.3_掛載階段
目標(biāo): 掌握掛載階段2個(gè)鉤子函數(shù)作用和執(zhí)行時(shí)機(jī)
含義講解:
1.template選項(xiàng)檢查
? 有 - 編譯template返回render渲染函數(shù)
? 無 – 編譯el選項(xiàng)對應(yīng)標(biāo)簽作為template(要渲染的模板)
2.虛擬DOM掛載成真實(shí)DOM之前
3.beforeMount – 生命周期鉤子函數(shù)被執(zhí)行
4.Create … – 把虛擬DOM和渲染的數(shù)據(jù)一并掛到真實(shí)DOM上
5.真實(shí)DOM掛載完畢
6.mounted – 生命周期鉤子函數(shù)被執(zhí)行
components/Life.vue - 創(chuàng)建一個(gè)文件
<template> <div> <p>學(xué)習(xí)生命周期 - 看控制臺打印</p> <p id="myP">{{ msg }}</p> </div> </template> <script> export default { // ...省略其他代碼 // 二. 掛載 // 真實(shí)DOM掛載之前 // 場景: 預(yù)處理data, 不會(huì)觸發(fā)updated鉤子函數(shù) beforeMount(){ console.log("beforeMount -- 執(zhí)行"); console.log(document.getElementById("myP")); // null this.msg = "重新值" }, // 真實(shí)DOM掛載以后 // 場景: 掛載后真實(shí)DOM mounted(){ console.log("mounted -- 執(zhí)行"); console.log(document.getElementById("myP")); // p } } </script>
1.4_更新階段
目標(biāo): 掌握更新階段2個(gè)鉤子函數(shù)作用和執(zhí)行時(shí)機(jī)
含義講解:
1.當(dāng)data里數(shù)據(jù)改變, 更新DOM之前
2.beforeUpdate – 生命周期鉤子函數(shù)被執(zhí)行
3.Virtual DOM…… – 虛擬DOM重新渲染, 打補(bǔ)丁到真實(shí)DOM
4.updated – 生命周期鉤子函數(shù)被執(zhí)行
5.當(dāng)有data數(shù)據(jù)改變 – 重復(fù)這個(gè)循環(huán)
components/Life.vue - 創(chuàng)建一個(gè)文件
準(zhǔn)備ul+li循環(huán), 按鈕添加元素, 觸發(fā)data改變->導(dǎo)致更新周期開始
<template> <div> <p>學(xué)習(xí)生命周期 - 看控制臺打印</p> <p id="myP">{{ msg }}</p> <ul id="myUL"> <li v-for="(val, index) in arr" :key="index"> {{ val }} </li> </ul> <button @click="arr.push(1000)">點(diǎn)擊末尾加值</button> </div> </template> <script> export default { data(){ return { msg: "hello, Vue", arr: [5, 8, 2, 1] } }, // ...省略其他代碼 // 三. 更新 // 前提: data數(shù)據(jù)改變才執(zhí)行 // 更新之前 beforeUpdate(){ console.log("beforeUpdate -- 執(zhí)行"); console.log(document.querySelectorAll("#myUL>li")[4]); // undefined }, // 更新之后 // 場景: 獲取更新后的真實(shí)DOM updated(){ console.log("updated -- 執(zhí)行"); console.log(document.querySelectorAll("#myUL>li")[4]); // li } } </script>
1.5_銷毀階段
目標(biāo): 掌握銷毀階段2個(gè)鉤子函數(shù)作用和執(zhí)行時(shí)機(jī)
含義講解:
1.當(dāng)$destroy()被調(diào)用 – 比如組件DOM被移除(例v-if)
2.beforeDestroy – 生命周期鉤子函數(shù)被執(zhí)行
3.拆卸數(shù)據(jù)監(jiān)視器、子組件和事件偵聽器
4.實(shí)例銷毀后, 最后觸發(fā)一個(gè)鉤子函數(shù)
5.destroyed – 生命周期鉤子函數(shù)被執(zhí)行
components/Life.vue - 準(zhǔn)備生命周期方法(Life組件即將要被刪除)
<script> export default { // ...省略其他代碼 // 四. 銷毀 // 前提: v-if="false" 銷毀Vue實(shí)例 // 場景: 移除全局事件, 移除當(dāng)前組件, 計(jì)時(shí)器, 定時(shí)器, eventBus移除事件$off方法 beforeDestroy(){ // console.log('beforeDestroy -- 執(zhí)行'); clearInterval(this.timer) }, destroyed(){ // console.log("destroyed -- 執(zhí)行"); } } </script>
主要: App.vue - 點(diǎn)擊按鈕讓Life組件從DOM上移除 -> 導(dǎo)致Life組件進(jìn)入銷毀階段
<Life v-if="show"></Life> <button @click="show = false">銷毀組件</button> <script> data(){ return { show: true } }, </script>
2. axios
2.0_axios基本使用
特點(diǎn)
- 支持客戶端發(fā)送Ajax請求
- 支持服務(wù)端Node.js發(fā)送請求
- 支持Promise相關(guān)用法
- 支持請求和響應(yīng)的攔截器功能
- 自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)
- axios 底層還是原生js實(shí)現(xiàn), 內(nèi)部通過Promise封裝的
axios的基本使用
axios({ method: '請求方式', // get post url: '請求地址', data: { // 拼接到請求體的參數(shù), post請求的參數(shù) xxx: xxx, }, params: { // 拼接到請求行的參數(shù), get請求的參數(shù) xxx: xxx } }).then(res => { console.log(res.data) // 后臺返回的結(jié)果 }).catch(err => { console.log(err) // 后臺報(bào)錯(cuò)返回 })
2.1_axios基本使用-獲取數(shù)據(jù)
目標(biāo): 調(diào)用文檔最后_獲取所有圖書信息接口
功能: 點(diǎn)擊調(diào)用后臺接口, 拿到所有數(shù)據(jù) – 打印到控制臺
接口: 參考預(yù)習(xí)資料.md – 接口文檔
引入: 下載axios, 引入后才能使用
效果:
例子如下:
components/UseAxios.vue
<template> <div> <p>1. 獲取所有圖書信息</p> <button @click="getAllFn">點(diǎn)擊-查看控制臺</button> </div> </template> <script> // 目標(biāo)1: 獲取所有圖書信息 // 1. 下載axios // 2. 引入axios // 3. 發(fā)起axios請求 import axios from "axios"; export default { methods: { getAllFn() { axios({ url: "http://123.57.109.30:3006/api/getbooks", method: "GET", // 默認(rèn)就是GET方式請求, 可以省略不寫 }).then((res) => { console.log(res); }); // axios()-原地得到Promise對象 }, } }; </script>
2.2_axios基本使用-傳參
目標(biāo): 調(diào)用接口-獲取某本書籍信息
功能: 點(diǎn)擊調(diào)用后臺接口, 查詢用戶想要的書籍信息 – 打印到控制臺
接口: 參考預(yù)習(xí)資料.md – 接口文檔
效果:
例子如下:
components/UseAxios.vue
<template> <div> <p>2. 查詢某本書籍信息</p> <input type="text" placeholder="請輸入要查詢 的書名" v-model="bName" /> <button @click="findFn">查詢</button> </div> </template> <script> import axios from "axios"; export default { data() { return { bName: "" }; }, methods: { // ...省略了查詢所有的代碼 findFn() { axios({ url: "/api/getbooks", method: "GET", params: { // 都會(huì)axios最終拼接到url?后面 bookname: this.bName } }).then(res => { console.log(res); }) } }, }; </script>
2.3_axios基本使用-發(fā)布書籍
目標(biāo): 完成發(fā)布書籍功能
功能: 點(diǎn)擊新增按鈕, 把用戶輸入的書籍信息, 傳遞給后臺 – 把結(jié)果打印在控制臺
接口: 參考預(yù)習(xí)資料.md – 接口文檔
效果:
例子如下:
components/UseAxios.vue
<template> <div> <p>3. 新增圖書信息</p> <div> <input type="text" placeholder="書名" v-model="bookObj.bookname"> </div> <div> <input type="text" placeholder="作者" v-model="bookObj.author"> </div> <div> <input type="text" placeholder="出版社" v-model="bookObj.publisher"> </div> <button @click="sendFn">發(fā)布</button> </div> </template> <script> import axios from "axios"; export default { data() { return { bName: "", bookObj: { // 參數(shù)名提前和后臺的參數(shù)名對上-發(fā)送請求就不用再次對接了 bookname: "", author: "", publisher: "" } }; }, methods: { // ...省略了其他代碼 sendFn(){ axios({ url: "/api/addbook", method: "POST", data: { appkey: "7250d3eb-18e1-41bc-8bb2-11483665535a", ...this.bookObj // 等同于下面 // bookname: this.bookObj.bookname, // author: this.bookObj.author, // publisher: this.bookObj.publisher } }) } }, }; </script>
2.4_axios基本使用-全局配置
目標(biāo): 避免前綴基地址, 暴露在邏輯頁面里, 統(tǒng)一設(shè)置
axios.defaults.baseURL = "http://123.57.109.30:3006" // 所有請求的url前置可以去掉, 請求時(shí), axios會(huì)自動(dòng)拼接baseURL的地址在前面 getAllFn() { axios({ url: "/api/getbooks", method: "GET", // 默認(rèn)就是GET方式請求, 可以省略不寫 }).then((res) => { console.log(res); }); // axios()-原地得到Promise對象 },
3. nextTick和refs知識
3.0 $refs-獲取DOM
目標(biāo): 利用 ref 和 $refs 可以用于獲取 dom 元素
components/More.vue
<template> <div> <p>1. 獲取原生DOM元素</p> <h1 id="h" ref="myH">我是一個(gè)孤獨(dú)可憐又能吃的h1</h1> </div> </template> <script> // 目標(biāo): 獲取組件對象 // 1. 創(chuàng)建組件/引入組件/注冊組件/使用組件 // 2. 組件起別名ref // 3. 恰當(dāng)時(shí)機(jī), 獲取組件對象 export default { mounted(){ console.log(document.getElementById("h")); // h1 console.log(this.$refs.myH); // h1 } } </script> <style> </style>
總結(jié): 通過id / ref, 都可以獲取原生DOM標(biāo)簽
3.1 $refs-獲取組件對象
目標(biāo): 獲取組件對象, 調(diào)用組件里方法
components/Child/Demo.vue
<template> <div> <p>我是Demo組件</p> </div> </template> <script> export default { methods: { fn(){ console.log("demo組件內(nèi)的方法被調(diào)用了"); } } } </script>
More.vue - 獲取組件對象 - 調(diào)用組件方法
<template> <div> <p>1. 獲取原生DOM元素</p> <h1 id="h" ref="myH">我是一個(gè)孤獨(dú)可憐又能吃的h1</h1> <p>2. 獲取組件對象 - 可調(diào)用組件內(nèi)一切</p> <Demo ref="de"></Demo> </div> </template> <script> // 目標(biāo): 獲取組件對象 // 1. 創(chuàng)建組件/引入組件/注冊組件/使用組件 // 2. 組件起別名ref // 3. 恰當(dāng)時(shí)機(jī), 獲取組件對象 import Demo from './Child/Demo' export default { mounted(){ console.log(document.getElementById("h")); // h1 console.log(this.$refs.myH); // h1 let demoObj = this.$refs.de; demoObj.fn() }, components: { Demo } } </script>
總結(jié): ref定義值, 通過$refs.值 來獲取組件對象, 就能繼續(xù)調(diào)用組件內(nèi)的變量
3.2 $nextTick使用
Vue更新DOM-異步的
目標(biāo): 點(diǎn)擊count++, 馬上通過"原生DOM"拿標(biāo)簽內(nèi)容, 無法拿到新值
components/Move.vue - 繼續(xù)新增第三套代碼
<template> <div> <p>1. 獲取原生DOM元素</p> <h1 id="h" ref="myH">我是一個(gè)孤獨(dú)可憐又能吃的h1</h1> <p>2. 獲取組件對象 - 可調(diào)用組件內(nèi)一切</p> <Demo ref="de"></Demo> <p>3. vue更新DOM是異步的</p> <p ref="myP">{{ count }}</p> <button @click="btn">點(diǎn)擊count+1, 馬上提取p標(biāo)簽內(nèi)容</button> </div> </template> <script> // 目標(biāo): 獲取組件對象 // 1. 創(chuàng)建組件/引入組件/注冊組件/使用組件 // 2. 組件起別名ref // 3. 恰當(dāng)時(shí)機(jī), 獲取組件對象 import Demo from './Child/Demo' export default { mounted(){ console.log(document.getElementById("h")); // h1 console.log(this.$refs.myH); // h1 let demoObj = this.$refs.de; demoObj.fn() }, components: { Demo }, data(){ return { count: 0 } }, methods: { btn(){ this.count++; // vue監(jiān)測數(shù)據(jù)更新, 開啟一個(gè)DOM更新隊(duì)列(異步任務(wù)) console.log(this.$refs.myP.innerHTML); // 0 // 原因: Vue更新DOM異步 // 解決: this.$nextTick() // 過程: DOM更新完會(huì)挨個(gè)觸發(fā)$nextTick里的函數(shù)體 this.$nextTick(() => { console.log(this.$refs.myP.innerHTML); // 1 }) } } } </script>
總結(jié): 因?yàn)镈OM更新是異步的
3.3 $nextTick使用場景
目標(biāo): 點(diǎn)擊搜索按鈕, 彈出聚焦的輸入框, 按鈕消失
![ n e x t T i c k 使 用 ] (images/nextTick使用.gif)
components/Tick.vue
<template> <div> <input ref="myInp" type="text" placeholder="這是一個(gè)輸入框" v-if="isShow"> <button v-else @click="btn">點(diǎn)擊我進(jìn)行搜索</button> </div> </template> <script> // 目標(biāo): 點(diǎn)按鈕(消失) - 輸入框出現(xiàn)并聚焦 // 1. 獲取到輸入框 // 2. 輸入框調(diào)用事件方法focus()達(dá)到聚焦行為 export default { data(){ return { isShow: false } }, methods: { async btn(){ this.isShow = true; // this.$refs.myInp.focus() // 原因: data變化更新DOM是異步的 // 輸入框還沒有掛載到真實(shí)DOM上 // 解決: // this.$nextTick(() => { // this.$refs.myInp.focus() // }) // 擴(kuò)展: await取代回調(diào)函數(shù) // $nextTick()原地返回Promise對象 await this.$nextTick() this.$refs.myInp.focus() } } } </script>
3.4 組件name屬性使用
目標(biāo): 可以用組件的name屬性值, 來注冊組件名字
問題: 組件名不是可以隨便寫的?
答案: 我們封裝的組件-可以自己定義name屬性組件名-讓使用者有個(gè)統(tǒng)一的前綴風(fēng)格
components/Com.vue
<template> <div> <p>我是一個(gè)Com組件</p> </div> </template> <script> export default { name: "ComNameHaHa" // 注冊時(shí)可以定義自己的名字 } </script>
App.vue - 注冊和使用
<template> <div> <h1>1. 生命周期</h1> <Life v-if="show"></Life> <button @click="show = false">銷毀組件</button> <hr> <h1>2. axios使用</h1> <UseAxios></UseAxios> <hr> <h1>3. $refs的使用</h1> <More></More> <hr> <h1>4. $nextTick使用場景</h1> <Tick></Tick> <hr> <h1>5. 組件對象里name屬性</h1> <ComNameHaHa></ComNameHaHa> </div> </template> <script> import Life from './components/Life' import UseAxios from './components/UseAxios' import More from './components/More' import Tick from './components/Tick' import Com from './components/Com' export default { data(){ return { show: true } }, components: { Life, UseAxios, More, Tick, [Com.name]: Com // 對象里的key是變量的話[]屬性名表達(dá)式 // "ComNameHaHa": Com } } </script>
4. 案例 - 購物車
4.0 案例-購物車-項(xiàng)目初始化
目標(biāo): 初始化新項(xiàng)目, 清空不要的東西, 下載bootstrap庫, 下載less模塊
vue create shopcar yarn add bootstrap yarn add less less-loader@5.0.0 -D
圖示:
按照需求, 把項(xiàng)目頁面拆分成幾個(gè)組件, 在components下創(chuàng)建
- MyHeader組件
- MyFooter組件
- MyGoods組件 - 商品
- MyCount組件
然后引入到App.vue上注冊
在main.js中引入bootStrap庫
import "bootstrap/dist/css/bootstrap.css" // 引入第三方包里的某個(gè)css文件
MyHeader.vue
<template> <div class="my-header">購物車案例</div> </template> <script> export default { } </script> <style lang="less" scoped> .my-header { height: 45px; line-height: 45px; text-align: center; background-color: #1d7bff; color: #fff; position: fixed; top: 0; left: 0; width: 100%; z-index: 2; } </style>
MyGoods.vue
<template> <div class="my-goods-item"> <div class="left"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="input" > <label class="custom-control-label" for="input"> <img src="http://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg" alt=""> </label> </div> </div> <div class="right"> <div class="top">商品名字</div> <div class="bottom"> <span class="price">¥ 100</span> <span> 數(shù)量組件 </span> </div> </div> </div> </template> <script> export default { } </script> <style lang="less" scoped> .my-goods-item { display: flex; padding: 10px; border-bottom: 1px solid #ccc; .left { img { width: 120px; height: 120px; margin-right: 8px; border-radius: 10px; } .custom-control-label::before, .custom-control-label::after { top: 50px; } } .right { flex: 1; display: flex; flex-direction: column; justify-content: space-between; .top{ font-size: 14px; font-weight: 700; } .bottom { display: flex; justify-content: space-between; padding: 5px 0; align-items: center; .price { color: red; font-weight: bold; } } } } </style>
目標(biāo): 完成商品組件右下角商品組件的開發(fā)
components/MyCount.vue
<template> <div class="my-counter"> <button type="button" class="btn btn-light" >-</button> <input type="number" class="form-control inp" > <button type="button" class="btn btn-light">+</button> </div> </template> <script> export default { } </script> <style lang="less" scoped> .my-counter { display: flex; .inp { width: 45px; text-align: center; margin: 0 10px; } .btn, .inp{ transform: scale(0.9); } } </style>
components/MyFooter.vue
<template> <!-- 底部 --> <div class="my-footer"> <!-- 全選 --> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="footerCheck"> <label class="custom-control-label" for="footerCheck">全選</label> </div> <!-- 合計(jì) --> <div> <span>合計(jì):</span> <span class="price">¥ 0</span> </div> <!-- 按鈕 --> <button type="button" class="footer-btn btn btn-primary">結(jié)算 ( 0 )</button> </div> </template> <script> export default { } </script> <style lang="less" scoped> .my-footer { position: fixed; z-index: 2; bottom: 0; width: 100%; height: 50px; border-top: 1px solid #ccc; display: flex; justify-content: space-between; align-items: center; padding: 0 10px; background: #fff; .price { color: red; font-weight: bold; font-size: 15px; } .footer-btn { min-width: 80px; height: 30px; line-height: 30px; border-radius: 25px; padding: 0; } } </style>
4.1 案例-購物車-頭部自定義
目的: 頭部的標(biāo)題, 顏色, 背景色可以隨便修改, props類型的校驗(yàn)
思路
- 在MyHeader.vue中準(zhǔn)備props里變量, 然后使用
- 在使用MyHeader.vue組件時(shí), 傳入相應(yīng)的值 (color和backgroundColor)
MyHeader.vue
<template> <div class="my-header" :style="{backgroundColor: background, color}">{{ title }}</div> </template> <script> // 目標(biāo): 讓Header組件支持不同的項(xiàng)目 - 自定義 // 1. 分析哪些可以自定義 (背景色, 文字顏色, 文字內(nèi)容) // 2. (新) 可以對props的變量的值 進(jìn)行校驗(yàn) // 3. 內(nèi)部使用props變量的值 // 4. 外部使用時(shí), 遵守變量名作為屬性名, 值的類型遵守 export default { props: { background: String, // 外部插入此變量的值, 必須是字符串類型, 否則報(bào)錯(cuò) color: { type: String, // 約束color值的類型 default: "#fff" // color變量默認(rèn)值(外部不給 我color傳值, 使用默認(rèn)值) }, title: { type: String, required: true // 必須傳入此變量的值 } } } </script> <style lang="less" scoped> .my-header { height: 45px; line-height: 45px; text-align: center; background-color: #1d7bff; color: #fff; position: fixed; top: 0; left: 0; width: 100%; z-index: 2; } </style>
App.vue傳入相應(yīng)自定義的值
<MyHeader title="購物車案例"></MyHeader>
總結(jié):
props: [] - 只能聲明變量和接收, 不能類型校驗(yàn)
props: {} - 聲明變量和校驗(yàn)類型規(guī)則 - 外部傳入值不對則報(bào)錯(cuò)
4.2 案例-購物車-請求數(shù)據(jù)
目標(biāo): 使用axios把數(shù)據(jù)請求回來
數(shù)據(jù)地址: https://www.escook.cn/api/cart (get方式)
下載axios
yarn add axios
main.js - 原型上掛載
// 目標(biāo): 請求數(shù)據(jù) - 打印 // 1. 下載axios庫, main.js - 全局綁定屬性 (確保任意.vue文件可以都訪問到這個(gè)axios方法) import axios from 'axios' // 2. 基礎(chǔ)地址 axios.defaults.baseURL = "https://www.escook.cn" // 3. axios方法添加到Vue的原型上 Vue.prototype.$axios = axios new Vue({ render: h => h(App), }).$mount('#app')
App.vue請求使用
<script> export default { data(){ return { list: [] // 商品所有數(shù)據(jù) } }, created(){ // 不必在自己引入axios變量, 而是直接使用全局屬性$axios this.$axios({ url: "/api/cart" }).then(res => { console.log(res); this.list = res.data.list }) } } </script>
總結(jié): 利用axios, 調(diào)用接口, 把數(shù)據(jù)請求回來
4.3 案例-購物車-數(shù)據(jù)渲染
目標(biāo): 把上面請求的數(shù)據(jù), 鋪設(shè)到頁面上
App.vue
<MyGoods v-for="obj in list" :key="obj.id" :gObj="obj" ></MyGoods>
MyGoods.vue
<template> <div class="my-goods-item"> <div class="left"> <div class="custom-control custom-checkbox"> <!-- *重要: 每個(gè)對象和組件都是獨(dú)立的 對象里的goods_state關(guān)聯(lián)自己對應(yīng)商品的復(fù)選框 --> <!-- bug: 循環(huán)的所有l(wèi)abel的for都是input, id也都是input - 默認(rèn)只有第一個(gè)生效 解決: 每次對象里的id值(1, 2), 分別給id和for使用即可區(qū)分 --> <input type="checkbox" class="custom-control-input" :id="gObj.id" v-model="gObj.goods_state" > <label class="custom-control-label" :for="gObj.id"> <img :src="gObj.goods_img" alt=""> </label> </div> </div> <div class="right"> <div class="top">{{ gObj.goods_name }}</div> <div class="bottom"> <span class="price">¥ {{ gObj.goods_price }}</span> <span> <MyCount :obj="gObj"></MyCount> </span> </div> </div> </div> </template> <script> import MyCount from './MyCount' export default { props: { gObj: Object }, components: { MyCount } } </script>
MyCount.vue
<template> <div class="my-counter"> <button type="button" class="btn btn-light" >-</button> <input type="number" class="form-control inp" v-model.number="obj.goods_count"> <button type="button" class="btn btn-light" >+</button> </div> </template> <script> export default { props: { obj: Object // 商品對象 } } </script>
總結(jié): 把各個(gè)組件關(guān)聯(lián)起來, 把數(shù)據(jù)都鋪設(shè)到頁面上
4.4 案例-購物車-商品選中
問題: 點(diǎn)擊發(fā)現(xiàn)總是第一個(gè)被選中
原來id和for都是"input"
但是id是唯一的啊, 所以用數(shù)據(jù)的id來作為標(biāo)簽的id, 分別獨(dú)立, 為了兼容label點(diǎn)擊圖片也能選中的效果
<input type="checkbox" class="custom-control-input" :id="gObj.id" v-model="gObj.goods_state" > <label class="custom-control-label" :for="gObj.id"> <img :src="gObj.goods_img" alt=""> </label>
總結(jié): lable的for值對應(yīng)input的id, 點(diǎn)擊label就能讓對應(yīng)input處于激活
4.5 案例-購物車-數(shù)量控制
目標(biāo): 點(diǎn)擊+和-或者直接修改輸入框的值影響商品購買的數(shù)量
<template> <div class="my-counter"> <button type="button" class="btn btn-light" :disabled="obj.goods_count === 1" @click="obj.goods_count > 1 && obj.goods_count--">-</button> <input type="number" class="form-control inp" v-model.number="obj.goods_count"> <button type="button" class="btn btn-light" @click="obj.goods_count++">+</button> </div> </template> <script> // 目標(biāo): 商品數(shù)量 - 控制 // 1. 外部傳入數(shù)據(jù)對象 // 2. v-model關(guān)聯(lián)對象的goods_count屬性和輸入框 (雙向綁定) // 3. 商品按鈕 +和-, 商品數(shù)量最少1件 // 4. 偵聽數(shù)量改變, 小于1, 直接強(qiáng)制覆蓋1 export default { props: { obj: Object // 商品對象 }, // 因?yàn)閿?shù)量控制要通過對象"互相引用的關(guān)系"來影響外面對象里的數(shù)量值, 所以最好傳 對象進(jìn)來 watch: { obj: { deep: true, handler(){ // 拿到商品數(shù)量, 判斷小于1, 強(qiáng)制修改成1 if (this.obj.goods_count < 1) { this.obj.goods_count = 1 } } } } } </script>
4.6 案例-購物車-全選功能
目標(biāo): 在底部組件上, 完成全選功能
思路:
點(diǎn)擊獲取它的選中狀態(tài)同步給上面每個(gè)小選框 - 而小選框的選中狀態(tài)又在數(shù)組里把數(shù)組傳給MyFooter, 然后更新即可 - 因?yàn)閷ο蠖际且藐P(guān)系的
MyFooter.vue
<template> <!-- 底部 --> <div class="my-footer"> <!-- 全選 --> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="footerCheck" v-model="isAll"> <label class="custom-control-label" for="footerCheck">全選</label> </div> <!-- 合計(jì) --> <div> <span>合計(jì):</span> <span class="price">¥ {{ allPrice }}</span> </div> <!-- 按鈕 --> <button type="button" class="footer-btn btn btn-primary">結(jié)算 ( {{ allCount }} )</button> </div> </template> <script> // 目標(biāo): 全選 // 1. v-model關(guān)聯(lián)全選-復(fù)選框(v-model后變量計(jì)算屬性) // 2. 頁面(視頻層)v(true) -> 數(shù)據(jù)層(變量-) 計(jì)算屬性(完整寫法) // 3. 把全選 true/false同步給所有小選框選中狀態(tài)上 // 小選 -> 全選 // App.vue里list數(shù)組 -> MyFooter.vue // isAll的get方法里, 統(tǒng)計(jì)狀態(tài)影響全選框 // 目標(biāo): 總數(shù)量統(tǒng)計(jì) // 1. allCount計(jì)算屬性用 數(shù)組reduce+判斷統(tǒng)計(jì)數(shù)量并返回 // 目標(biāo): 總價(jià) // allPrice計(jì)算屬性, 數(shù)組reduce+單價(jià)*數(shù)量, 判斷選中, 才累加后返回 export default { props: { arr: Array }, computed: { isAll: { set(val){ // val就是關(guān)聯(lián)表單的值(true/false) this.$emit('changeAll', val) }, get(){ // 查找小選框關(guān)聯(lián)的屬性有沒有不符合勾選的條件 // 直接原地false return this.arr.every(obj => obj.goods_state === true) } }, } } </script>
App.vue
<MyFooter @changeAll="allFn" :arr="list"></MyFooter> <script> methods: { allFn(bool){ this.list.forEach(obj => obj.goods_state = bool) // 把MyFooter內(nèi)的全選狀態(tài)true/false同步給所有小選框的關(guān)聯(lián)屬性上 } } </script>
總結(jié): 全選的v-model的值, 使用計(jì)算屬性完整寫法
4.7 案例-購物車-總數(shù)量
目標(biāo): 完成底部組件, 顯示選中的商品的總數(shù)量
MyFooter.vue
allCount(){ return this.arr.reduce((sum, obj) => { if (obj.goods_state === true) { // 選中商品才累加數(shù)量 sum += obj.goods_count; } return sum; }, 0) },
總結(jié): 對象之間是引用關(guān)系, 對象值改變, 所有用到的地方都跟著改變
4.8 案例-購物車-總價(jià)
目標(biāo): 完成選中商品計(jì)算價(jià)格
components/MyFooter.vue
allPrice(){ return this.arr.reduce((sum, obj) => { if (obj.goods_state){ sum += obj.goods_count * obj.goods_price } return sum; }, 0) }
總結(jié): 把數(shù)組傳給了MyFooter組件, 統(tǒng)計(jì)總價(jià)
面試題
1、Vue 的 nextTick 的原理是什么? (高薪常問)
? \1. 為什么需要 nextTick ,Vue 是異步修改 DOM 的并且不鼓勵(lì)開發(fā)者直接接觸 DOM,但有時(shí)候業(yè)務(wù)需要必須對數(shù)據(jù)更改–刷新后的 DOM 做相應(yīng)的處理,這時(shí)候就可以使用 Vue.nextTick(callback)這個(gè) api 了。
? \2. 理解原理前的準(zhǔn)備 首先需要知道事件循環(huán)中宏任務(wù)和微任務(wù)這兩個(gè)概念,常見的宏任務(wù)有 script, setTimeout, setInterval, setImmediate, I/O, UI rendering 常見的微任務(wù)有 process.nextTick(Nodejs),Promise.then(), MutationObserver;
? \3. 理解 nextTick 的原理正是 vue 通過異步隊(duì)列控制 DOM 更新和 nextTick 回調(diào)函數(shù)先后執(zhí)行的方式。如果大家看過這部分的源碼,會(huì)發(fā)現(xiàn)其中做了很多 isNative()的判斷,因?yàn)檫@里還存在兼容性優(yōu)雅降級的問題??梢?Vue 開發(fā)團(tuán)隊(duì)的深思熟慮,對性能的良苦用心。
2、vue生命周期總共分為幾個(gè)階段?(必會(huì))
Vue 實(shí)例從創(chuàng)建到銷毀的過程,就是生命周期。也就是從開始創(chuàng)建、初始化數(shù)據(jù)、編譯模板、掛載Dom→渲染、更新→渲染、卸載等一系列過程,我們稱這是 Vue 的生命周期。
1**)beforeCreate**
? 在實(shí)例初始化之后,數(shù)據(jù)觀測 (data observer) 和 event/watcher 事件配置之前被調(diào)用。
2**)created**
? 在實(shí)例創(chuàng)建完成后被立即調(diào)用。在這一步,實(shí)例已完成以下的配置:數(shù)據(jù)觀測 (data observer), 屬性和方法的運(yùn)算,watch/event 事件回調(diào)。然而,掛載階段還沒開始,$el 屬性目前不可見。
3**)beforeMount**
? 在掛載開始之前被調(diào)用:相關(guān)的 render 函數(shù)首次被調(diào)用。
4**)mounted**
? el 被新創(chuàng)建的 vm. e l 替 換 , 并 掛 載 到 實(shí) 例 上 去 之 后 調(diào) 用 該 鉤 子 。 如 果 r o o t 實(shí) 例 掛 載 了 一 個(gè) 文 檔 內(nèi) 元 素 , 當(dāng) m o u n t e d 被 調(diào) 用 時(shí) v m . el 替換,并掛載到實(shí)例上去之后調(diào)用該鉤子。如果 root 實(shí)例掛載了一個(gè)文檔內(nèi)元素,當(dāng) mounted 被調(diào)用時(shí) vm. el替換,并掛載到實(shí)例上去之后調(diào)用該鉤子。如果root實(shí)例掛載了一個(gè)文檔內(nèi)元素,當(dāng)mounted被調(diào)用時(shí)vm.el 也在文檔內(nèi)。
5**)beforeUpdate**
? 數(shù)據(jù)更新時(shí)調(diào)用,發(fā)生在虛擬 DOM 打補(bǔ)丁之前。這里適合在更新之前訪問現(xiàn)有的 DOM,比如手動(dòng)移除已添加的事件監(jiān)聽器。該鉤子在服務(wù)器端渲染期間不被調(diào)用,因?yàn)橹挥谐醮武秩緯?huì)在服務(wù)端進(jìn)行。
6**)updated**
? 由于數(shù)據(jù)更改導(dǎo)致的虛擬 DOM 重新渲染和打補(bǔ)丁,在這之后會(huì)調(diào)用該鉤子。
7**)activated**
? keep-alive 組件激活時(shí)調(diào)用。該鉤子在服務(wù)器端渲染期間不被調(diào)用。
8**)deactivated**
? keep-alive 組件停用時(shí)調(diào)用。該鉤子在服務(wù)器端渲染期間不被調(diào)用。
9**)beforeDestroy**
? 實(shí)例銷毀之前調(diào)用。在這一步,實(shí)例仍然完全可用。該鉤子在服務(wù)器端渲染期間不被調(diào)用。
10**)destroyed**
? Vue 實(shí)例銷毀后調(diào)用。調(diào)用后,Vue 實(shí)例指示的所有東西都會(huì)解綁定,所有的事件監(jiān)聽器會(huì)被移除,所有的子實(shí)例也會(huì)被銷毀。該鉤子在服務(wù)器端渲染期間不被調(diào)用。
11**)errorCaptured(2.5.0+ 新增)**
? 當(dāng)捕獲一個(gè)來自子孫組件的錯(cuò)誤時(shí)被調(diào)用。此鉤子會(huì)收到三個(gè)參數(shù):錯(cuò)誤對象、發(fā)生錯(cuò)誤的組件實(shí)例以及一個(gè)包含錯(cuò)誤來源信息的字符串。此鉤子可以返回 false 以阻止該錯(cuò)誤繼續(xù)向上傳播。
3、第一次加載頁面會(huì)觸發(fā)哪幾個(gè)鉤子函數(shù)?(必會(huì))
當(dāng)頁面第一次頁面加載時(shí)會(huì)觸發(fā) beforeCreate, created, beforeMount, mounted 這幾個(gè)鉤子函數(shù)
寫在最后
到此這篇關(guān)于一篇文章帶你吃透Vue生命周期的文章就介紹到這了,更多相關(guān)Vue生命周期內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue el-autocomplete遠(yuǎn)程搜索下拉框并實(shí)現(xiàn)自動(dòng)填充功能(推薦)
在elementui Input輸入框中可以找到遠(yuǎn)程搜索組件,獲取服務(wù)端的數(shù)據(jù)。這篇文章主要給大家介紹Vue el-autocomplete遠(yuǎn)程搜索下拉框并實(shí)現(xiàn)自動(dòng)填充功能,感興趣的朋友一起看看吧2019-10-10使用vue3+vite導(dǎo)入圖片路徑錯(cuò)亂問題排查及解決
使用vue3+vite開發(fā)的時(shí)候,導(dǎo)入svg圖片時(shí),同一個(gè)文件夾下的文件,其中一個(gè)路徑正常解析,另一個(gè)不行,更改文件名之后,該圖片文件就可以正常解析了,本文給大家介紹了使用vue3+vite導(dǎo)入圖片路徑錯(cuò)亂問題排查及解決,需要的朋友可以參考下2024-03-03Vue?vant-ui使用van-uploader實(shí)現(xiàn)頭像上傳功能
這篇文章主要介紹了Vue?vant-ui使用van-uploader實(shí)現(xiàn)頭像圖片上傳,項(xiàng)目中是使用有贊vant-ui框架實(shí)現(xiàn)的頭像上傳替換功能,用到了封裝的圖片壓縮封裝之后再去上傳圖片this.$imgUpload.imgZip(),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2022-05-05vue項(xiàng)目中使用vue-i18n報(bào)錯(cuò)的解決方法
這篇文章主要給大家介紹了關(guān)于vue項(xiàng)目中使用vue-i18n報(bào)錯(cuò)的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01vue?動(dòng)態(tài)路由component?傳遞變量報(bào)錯(cuò)問題解決
這篇文章主要為大家介紹了vue?動(dòng)態(tài)路由component?傳遞變量報(bào)錯(cuò)問題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05vue2 前后端分離項(xiàng)目ajax跨域session問題解決方法
本篇文章主要介紹了vue2 前后端分離項(xiàng)目ajax跨域session問題解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04vue遞歸組件實(shí)現(xiàn)樹形結(jié)構(gòu)
這篇文章主要為大家詳細(xì)介紹了vue遞歸組件實(shí)現(xiàn)樹形結(jié)構(gòu),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-09-09