本篇文章將我學(xué)習(xí)Vue期間掌握的好幾個(gè)提高開(kāi)發(fā)效率和性能的小技巧分享給大家,希望對(duì)大家有所幫助!
1. 巧用$attrs
和$listeners
$attrs
用于記錄從父組件傳入子組件的所有不被props
捕獲以及不是class
與style
的參數(shù),而$listeners
用于記錄從父組件傳入的所有不含.native
修飾器的事件。(學(xué)習(xí)視頻分享:vuejs視頻教程)
那下面的代碼作例子:
Vue.component('child', { props: ['title'], template: '<h3>{{ title }}</h3>' }) new Vue({ data:{a:1,title:'title'}, methods:{ handleClick(){ // ... }, handleChange(){ // ... } }, template:' <child class="child-width" :a="a" b="1" :title="title" @click.native="handleClick" @change="handleChange">', })
則在<child/>
在中
attrs
的值為{a:1,b:"1"}
listeners
的值為{change: handleChange}
通常我們可以用$attrs
和$listeners
作組件通信,在二次封裝組件中使用時(shí)比較高效,如:
Vue.component("custom-dialog", { // 通過(guò)v-bind="$attrs"和v-on="$listeners"把父組件傳入的參數(shù)和事件都注入到el-dialog實(shí)例上 template: '<el-dialog v-bind="$attrs" v-on="$listeners"></el-dialog>', }); new Vue({ data: { visible: false }, // 這樣子就可以像在el-dialog一樣用visible控制custom-dialog的顯示和消失 template: '<custom-dialog :visible.sync="visible">', });
再舉個(gè)例子:
Vue.component("custom-select", { template: `<el-select v-bind="$attrs" v-on="$listeners"> <el-option value="選項(xiàng)1" label="黃金糕"/> <el-option value="選項(xiàng)2" label="雙皮奶"/> </el-select>`, }); new Vue({ data: { value: "" }, // v-model在這里其實(shí)是v-bind:value和v-on:change的組合, // 在custom-select里,通過(guò)v-bind="$attrs" v-on="$listeners"的注入, // 把父組件上的value值雙向綁定到custom-select組件里的el-select上,相當(dāng)于<el-select v-model="value"> // 與此同時(shí),在custom-select注入的size變量也會(huì)通過(guò)v-bind="$attrs"注入到el-select上,從而控制el-select的大小 template: '<custom-select v-model="value" size="small">', });
2. 巧用$props
$porps
用于記錄從父組件傳入子組件的所有被props
捕獲以及不是class
與style
的參數(shù)。如
Vue.component('child', { props: ['title'], template: '<h3>{{ title }}</h3>' }) new Vue({ data:{a:1,title:'title'}, methods:{ handleClick(){ // ... }, handleChange(){ // ... } }, template:' <child class="child-width" :a="a" b="1" :title="title">', })
則在<child/>
在中,$props
的值為{title:'title'}
。$props
可以用于自組件和孫組件定義的props
都相同的情況,如:
Vue.component('grand-child', { props: ['a','b'], template: '<h3>{{ a + b}}</h3>' }) // child和grand-child都需要用到來(lái)自父組件的a與b的值時(shí), // 在child中可以通過(guò)v-bind="$props"迅速把a(bǔ)與b注入到grand-child里 Vue.component('child', { props: ['a','b'], template: ` <div> {{a}}加{}的和是: <grand-child v-bind="$props"/> </div> ` }) new Vue({ template:' <child class="child-width" :a="1" :b="2">', })
3. 妙用函數(shù)式組件
函數(shù)式組件相比于一般的vue
組件而言,最大的區(qū)別是非響應(yīng)式的。它不會(huì)監(jiān)聽(tīng)任何數(shù)據(jù),也沒(méi)有實(shí)例(因此沒(méi)有狀態(tài),意味著不存在諸如created
,mounted
的生命周期)。好處是因只是函數(shù),故渲染開(kāi)銷(xiāo)也低很多。
把開(kāi)頭的例子改成函數(shù)式組件,代碼如下:
<script> export default { name: "anchor-header", functional: true, // 以functional:true聲明該組件為函數(shù)式組件 props: { level: Number, name: String, content: String, }, // 對(duì)于函數(shù)式組件,render函數(shù)會(huì)額外傳入一個(gè)context參數(shù)用來(lái)表示上下文,即替代this。函數(shù)式組件沒(méi)有實(shí)例,故不存在this render: function (createElement, context) { const anchor = { props: { content: String, name: String, }, template: '<a :id="name" :href="`#${name}`"> {{content}}</a>', }; const anchorEl = createElement(anchor, { props: { content: context.props.content, //通過(guò)context.props調(diào)用props傳入的變量 name: context.props.name, }, }); const el = createElement(`h${context.props.level}`, [anchorEl]); return el; }, }; </script>
4. 妙用 Vue.config.devtools
其實(shí)我們?cè)谏a(chǎn)環(huán)境下也可以調(diào)用vue-devtools
去進(jìn)行調(diào)試,只要更改Vue.config.devtools
配置既可,如下所示:
// 務(wù)必在加載 Vue 之后,立即同步設(shè)置以下內(nèi)容 // 該配置項(xiàng)在開(kāi)發(fā)版本默認(rèn)為 `true`,生產(chǎn)版本默認(rèn)為 `false` Vue.config.devtools = true;
我們可以通過(guò)檢測(cè)cookie
里的用戶(hù)角色信息去決定是否開(kāi)啟該配置項(xiàng),從而提高線上 bug 查找的便利性。
5. 妙用 methods
Vue
中的method
可以賦值為高階函數(shù)返回的結(jié)果,例如:
<script> import { debounce } from "lodash"; export default { methods: { search: debounce(async function (keyword) { // ... 請(qǐng)求邏輯 }, 500), }, }; </script>
上面的search
函數(shù)賦值為debounce
返回的結(jié)果,也就是具有防抖功能的請(qǐng)求函數(shù)。這種方式可以避免我們?cè)诮M件里要自己寫(xiě)一遍防抖邏輯。
這里有個(gè)例子sandbox,大家可以點(diǎn)進(jìn)去看看經(jīng)過(guò)高階函數(shù)處理的method
與原始method
的效果區(qū)別,如下所示:
除此之外,method
還可以定義為生成器,如果我們有個(gè)函數(shù)需要執(zhí)行時(shí)很強(qiáng)調(diào)順序,而且需要在data
里定義變量來(lái)記錄上一次的狀態(tài),則可以考慮用生成器。
例如有個(gè)很常見(jiàn)的場(chǎng)景:微信的視頻通話(huà)在接通的時(shí)候會(huì)顯示計(jì)時(shí)器來(lái)記錄通話(huà)時(shí)間,這個(gè)通話(huà)時(shí)間需要每秒更新一次,即獲取通話(huà)時(shí)間的函數(shù)需要每秒執(zhí)行一次,如果寫(xiě)成普通函數(shù)則需要在data
里存放記錄時(shí)間的變量。但如果用生成器則能很巧妙地解決,如下所示:
<template> <div id="app"> <h3>{{ timeFormat }}</h3> </div> </template> <script> export default { name: "App", data() { return { // 用于顯示時(shí)間的變量,是一個(gè)HH:MM:SS時(shí)間格式的字符串 timeFormat: "", }; }, methods: { genTime: function* () { // 聲明存儲(chǔ)時(shí)、分、秒的變量 let hour = 0; let minute = 0; let second = 0; while (true) { // 遞增秒 second += 1; // 如果秒到60了,則分加1,秒清零 if (second === 60) { second = 0; minute += 1; } // 如果分到60了,則時(shí)加1,分清零 if (minute === 60) { minute = 0; hour += 1; } // 最后返回最新的時(shí)間字符串 yield `${hour}:${minute}:${second}`; } }, }, created() { // 通過(guò)生成器生成迭代器 const gen = this.genTime(); // 設(shè)置計(jì)時(shí)器定時(shí)從迭代器獲取最新的時(shí)間字符串 const timer = setInterval(() => { this.timeFormat = gen.next().value; }, 1000); // 在組件銷(xiāo)毀的時(shí)候清空定時(shí)器和迭代器以免發(fā)生內(nèi)存泄漏 this.$once("hook:beforeDestroy", () => { clearInterval(timer); gen = null; }); }, }; </script>
頁(yè)面效果如下所示:
代碼地址:https://codesandbox.io/s/jovial-williams-nkouf?file=/src/App.vue
但需要注意的是:method 不能是箭頭函數(shù)
注意,不應(yīng)該使用箭頭函數(shù)來(lái)定義
method
函數(shù) (例如plus: () => this.a++
)。理由是箭頭函數(shù)綁定了父級(jí)作用域的上下文,所以this
將不會(huì)按照期望指向 Vue 實(shí)例,this.a
將是undefined
。
6. 妙用 watch 的數(shù)組格式
很多開(kāi)發(fā)者會(huì)在watch
中某一個(gè)變量的handler
里調(diào)用多個(gè)操作,如下所示:
<script> export default { data() { return { value: "", }; }, methods: { fn1() {}, fn2() {}, }, watch: { value: { handler() { fn1(); fn2(); }, immediate: true, deep: true, }, }, }; </script>
雖然fn1
和fn2
都需要在value
變動(dòng)的時(shí)候調(diào)用,但兩者的調(diào)用時(shí)機(jī)可能不同。fn1
可能僅需要在deep
為false
的配置下調(diào)用既可。因此,Vue
在watch
的值添加了Array
類(lèi)型來(lái)針對(duì)上面所說(shuō)的情況,如果用watch
為Array
的寫(xiě)法處理可以寫(xiě)成下面這種形式:
<script> watch:{ 'value':[ { handler:function(){ fn1() }, immediate:true }, { handler:function(){ fn2() }, immediate:true, deep:true } ] } </script>
7. 妙用$options
$options
是一個(gè)記錄當(dāng)前Vue
組件的初始化屬性選項(xiàng)。通常開(kāi)發(fā)中,我們想把data
里的某個(gè)值重置為初始化時(shí)候的值,可以像下面這么寫(xiě):
this.value = this.$options.data().value;
這樣子就可以在初始值由于需求需要更改時(shí),只在data
中更改即可。
這里再舉一個(gè)場(chǎng)景:一個(gè)el-dialog
中有一個(gè)el-form
,我們要求每次打開(kāi)el-dialog
時(shí)都要重置el-form
里的數(shù)據(jù),則可以這么寫(xiě):
<template> <div> <el-button @click="visible=!visible">打開(kāi)彈窗</el-button> <el-dialog @open="initForm" title="個(gè)人資料" :visible.sync="visible"> <el-form> <el-form-item label="名稱(chēng)"> <el-input v-model="form.name"/> </el-form-item> <el-form-item label="性別"> <el-radio-group v-model="form.gender"> <el-radio label="male">男</el-radio> <el-radio label="female">女</el-radio> </el-radio-group> </el-form-item> </el-form> </el-dialog> </div> </template> <script> export default { name: "App", data(){ return { visible: false, form: { gender: 'male', name: 'wayne' } } }, methods:{ initForm(){ this.form = this.$options.data().form } } }; </script>
每次el-dialog
打開(kāi)之前都會(huì)調(diào)用其@open
中的方法initForm
,從而重置form
值到初始值。如下效果所示:
以上代碼放在sanbox里
如果要重置data
里的所有值,可以像下面這么寫(xiě):
Object.assign(this.$data, this.$options.data()); // 注意千萬(wàn)不要寫(xiě)成下面的樣子,這樣子就更改this.$data的指向。使得其指向另外的與組件脫離的狀態(tài) this.$data = this.$options.data();
8. 妙用 v-pre,v-once
v-pre
v-pre
用于跳過(guò)被標(biāo)記的元素以及其子元素的編譯過(guò)程,如果一個(gè)元素自身及其自元素非常打,而又不帶任何與Vue
相關(guān)的響應(yīng)式邏輯,那么可以用v-pre
標(biāo)記。標(biāo)記后效果如下:
v-once
只渲染元素和組件一次。隨后的重新渲染,元素/組件及其所有的子節(jié)點(diǎn)將被視為靜態(tài)內(nèi)容并跳過(guò)。這可以用于優(yōu)化更新性能。
對(duì)于部分在首次渲染后就不會(huì)再有響應(yīng)式變化的元素,可以用v-once
屬性去標(biāo)記,如下:
<el-select> <el-option v-for="item in options" v-once :key="item.value" :label="item.label" :value="item.value" >{{i}}</el-option > </el-select>
如果上述例子中的變量options
很大且不會(huì)再有響應(yīng)式變化,那么如例子中用上v-once
對(duì)性能有提升。
9. 妙用 hook 事件
如果想監(jiān)聽(tīng)子組件的生命周期時(shí),可以像下面例子中這么做:
<template> <child @hook:mounted="removeLoading" /> </template>
這樣的寫(xiě)法可以用于處理加載第三方的初始化過(guò)程稍漫長(zhǎng)的子組件時(shí),我們可以加loading
動(dòng)畫(huà),等到子組件加載完畢,到了mounted
生命周期時(shí),把loading
動(dòng)畫(huà)移除。
初次之外hook
還有一個(gè)常用的寫(xiě)法,在一個(gè)需要輪詢(xún)更新數(shù)據(jù)的組件上,我們通常在created
里開(kāi)啟定時(shí)器,然后在beforeDestroy
上清除定時(shí)器。而通過(guò)hook
,開(kāi)啟和銷(xiāo)毀定時(shí)器的邏輯我們都可以在created
里實(shí)現(xiàn):
<script> export default { created() { const timer = setInterval(() => { // 更新邏輯 }, 1000); // 通過(guò)$once和hook監(jiān)聽(tīng)實(shí)例自身的beforeDestroy,觸發(fā)該生命周期時(shí)清除定時(shí)器 this.$once("hook:beforeDestroy", () => { clearInterval(timer); }); }, }; </script>
像上面這種寫(xiě)法就保證了邏輯的統(tǒng)一,遵循了單一職責(zé)原則。
(學(xué)習(xí)視頻分享:web前端開(kāi)發(fā)、編程基礎(chǔ)視頻)