Vue开发技巧汇总
路由參數(shù)解耦
一般在組件內(nèi)使用路由參數(shù),大多數(shù)人會(huì)這樣做:
export default {methods: {getParamsId() {return this.$route.params.id}} }在組件中使用?$route?會(huì)使之與其對(duì)應(yīng)路由形成高度耦合,從而使組件只能在某些特定的 URL 上使用,限制了其靈活性。
正確的做法是通過(guò)?props?解耦
const router = new VueRouter({routes: [{path: '/user/:id',component: User,props: true}] })將路由的?props?屬性設(shè)置為?true?后,組件內(nèi)可通過(guò)?props?接收到params?參數(shù)
export default {props: ['id'],methods: {getParamsId() {return this.id}} }另外你還可以通過(guò)函數(shù)模式來(lái)返回?props
const router = new VueRouter({routes: [{path: '/user/:id',component: User,props: (route) => ({id: route.query.id})}] })文檔:router.vuejs.org/zh/guide/es…
函數(shù)式組件
函數(shù)式組件是無(wú)狀態(tài),它無(wú)法實(shí)例化,沒(méi)有任何的生命周期和方法。創(chuàng)建函數(shù)式組件也很簡(jiǎn)單,只需要在模板添加?functional?聲明即可。一般適合只依賴于外部數(shù)據(jù)的變化而變化的組件,因其輕量,渲染性能也會(huì)有所提高。
組件需要的一切都是通過(guò)?context?參數(shù)傳遞。它是一個(gè)上下文對(duì)象,具體屬性查看文檔。這里?props?是一個(gè)包含所有綁定屬性的對(duì)象。
函數(shù)式組件
<template functional><div class="list"><div class="item" v-for="item in props.list" :key="item.id" @click="props.itemClick(item)"><p>{{item.title}}</p><p>{{item.content}}</p></div></div> </template>父組件使用
<template><div><List :list="list" :itemClick="item => (currentItem = item)" /></div> </template> import List from '@/components/List.vue' export default {components: {List},data() {return {list: [{title: 'title',content: 'content'}],currentItem: ''}} }文檔:cn.vuejs.org/v2/guide/re…
樣式穿透
在開(kāi)發(fā)中修改第三方組件樣式是很常見(jiàn),但由于?scoped?屬性的樣式隔離,可能需要去除?scoped?或是另起一個(gè)?style?。這些做法都會(huì)帶來(lái)副作用(組件樣式污染、不夠優(yōu)雅),樣式穿透在css預(yù)處理器中使用才生效。
我們可以使用?>>>?或?/deep/?解決這一問(wèn)題:
<style scoped> 外層 >>> .el-checkbox {display: block;font-size: 26px;.el-checkbox__label {font-size: 16px;} } </style> <style scoped> /deep/ .el-checkbox {display: block;font-size: 26px;.el-checkbox__label {font-size: 16px;} } </style>watch高階使用
立即執(zhí)行
watch?是在監(jiān)聽(tīng)屬性改變時(shí)才會(huì)觸發(fā),有些時(shí)候,我們希望在組件創(chuàng)建后?watch?能夠立即執(zhí)行
可能想到的的方法就是在?create?生命周期中調(diào)用一次,但這樣的寫(xiě)法不優(yōu)雅,或許我們可以使用這樣的方法
export default {data() {return {name: 'Joe'}},watch: {name: {handler: 'sayName',immediate: true}},methods: {sayName() {console.log(this.name)}} }深度監(jiān)聽(tīng)
在監(jiān)聽(tīng)對(duì)象時(shí),對(duì)象內(nèi)部的屬性被改變時(shí)無(wú)法觸發(fā)?watch?,我們可以為其設(shè)置深度監(jiān)聽(tīng)
export default {data: {studen: {name: 'Joe',skill: {run: {speed: 'fast'}}}},watch: {studen: {handler: 'sayName',deep: true}},methods: {sayName() {console.log(this.studen)}} }觸發(fā)監(jiān)聽(tīng)執(zhí)行多個(gè)方法
使用數(shù)組可以設(shè)置多項(xiàng),形式包括字符串、函數(shù)、對(duì)象
export default {data: {name: 'Joe'},watch: {name: ['sayName1',function(newVal, oldVal) {this.sayName2()},{handler: 'sayName3',immaediate: true}]},methods: {sayName1() {console.log('sayName1==>', this.name)},sayName2() {console.log('sayName2==>', this.name)},sayName3() {console.log('sayName3==>', this.name)}} }文檔:cn.vuejs.org/v2/api/#wat…
watch監(jiān)聽(tīng)多
watch本身無(wú)法監(jiān)聽(tīng)多個(gè)變量。但我們可以將需要監(jiān)聽(tīng)的多個(gè)變量通過(guò)計(jì)算屬性返回對(duì)象,再監(jiān)聽(tīng)這個(gè)對(duì)象來(lái)實(shí)現(xiàn)“監(jiān)聽(tīng)多個(gè)變量”
export default {data() {return {msg1: 'apple',msg2: 'banana'}},compouted: {msgObj() {const { msg1, msg2 } = thisreturn {msg1,msg2}}},watch: {msgObj: {handler(newVal, oldVal) {if (newVal.msg1 != oldVal.msg1) {console.log('msg1 is change')}if (newVal.msg2 != oldVal.msg2) {console.log('msg2 is change')}},deep: true}} }事件參數(shù)$event
$event?是事件對(duì)象的特殊變量,在一些場(chǎng)景能給我們實(shí)現(xiàn)復(fù)雜功能提供更多可用的參數(shù)
原生事件
在原生事件中表現(xiàn)和默認(rèn)的事件對(duì)象相同
<template><div><input type="text" @input="inputHandler('hello', $event)" /></div> </template> export default {methods: {inputHandler(msg, e) {console.log(e.target.value)}} }自定義事件
在自定義事件中表現(xiàn)為捕獲從子組件拋出的值
my-item.vue?:
export default {methods: {customEvent() {this.$emit('custom-event', 'some value')}} } 復(fù)制代碼App.vue
<template><div><my-item v-for="(item, index) in list" @custom-event="customEvent(index, $event)"></my-list></div> </template> export default {methods: {customEvent(index, e) {console.log(e) // 'some value'}} }文檔:cn.vuejs.org/v2/guide/ev…
cn.vuejs.org/v2/guide/co…
自定義組件雙向綁定
組件?model?選項(xiàng):
允許一個(gè)自定義組件在使用 v-model 時(shí)定制 prop 和 event。默認(rèn)情況下,一個(gè)組件上的 v-model 會(huì)把 value 用作 prop 且把 input 用作 event,但是一些輸入類型比如單選框和復(fù)選框按鈕可能想使用 value prop 來(lái)達(dá)到不同的目的。使用 model 選項(xiàng)可以回避這些情況產(chǎn)生的沖突。
input?默認(rèn)作為雙向綁定的更新事件,通過(guò)?$emit?可以更新綁定的值
<my-switch v-model="val"></my-switch> export default {props: {value: {type: Boolean,default: false}},methods: {switchChange(val) {this.$emit('input', val)}} }修改組件的?model?選項(xiàng),自定義綁定的變量和事件
<my-switch v-model="num" value="some value"></my-switch> export default {model: {prop: 'num',event: 'update'},props: {value: {type: String,default: ''},num: {type: Number,default: 0}},methods: {numChange() {this.$emit('update', this.num++)}} }文檔:cn.vuejs.org/v2/api/#mod…
監(jiān)聽(tīng)組件生命周期
通常我們監(jiān)聽(tīng)組件生命周期會(huì)使用?$emit?,父組件接收事件來(lái)進(jìn)行通知
子組件
export default {mounted() {this.$emit('listenMounted')} }父組件
<template><div><List @listenMounted="listenMounted" /></div> </template>其實(shí)還有一種簡(jiǎn)潔的方法,使用?@hook?即可監(jiān)聽(tīng)組件生命周期,組件內(nèi)無(wú)需做任何改變。同樣的,?created?、?updated?等也可以使用此方法。
<template><List @hook:mounted="listenMounted" /> </template>程序化的事件偵聽(tīng)器
比如,在頁(yè)面掛載時(shí)定義計(jì)時(shí)器,需要在頁(yè)面銷毀時(shí)清除定時(shí)器。這看起來(lái)沒(méi)什么問(wèn)題。但仔細(xì)一看?this.timer?唯一的作用只是為了能夠在?beforeDestroy?內(nèi)取到計(jì)時(shí)器序號(hào),除此之外沒(méi)有任何用處。
export default {mounted() {this.timer = setInterval(() => {console.log(Date.now())}, 1000)},beforeDestroy() {clearInterval(this.timer)} }如果可以的話最好只有生命周期鉤子可以訪問(wèn)到它。這并不算嚴(yán)重的問(wèn)題,但是它可以被視為雜物。
我們可以通過(guò)?$on?或?$once?監(jiān)聽(tīng)頁(yè)面生命周期銷毀來(lái)解決這個(gè)問(wèn)題:
export default {mounted() {this.creatInterval('hello')this.creatInterval('world')},creatInterval(msg) {let timer = setInterval(() => {console.log(msg)}, 1000)this.$once('hook:beforeDestroy', function() {clearInterval(timer)})} }使用這個(gè)方法后,即使我們同時(shí)創(chuàng)建多個(gè)計(jì)時(shí)器,也不影響效果。因?yàn)樗鼈儠?huì)在頁(yè)面銷毀后程序化的自主清除。
文檔:cn.vuejs.org/v2/guide/co…
手動(dòng)掛載組件
在一些需求中,手動(dòng)掛載組件能夠讓我們實(shí)現(xiàn)起來(lái)更加優(yōu)雅。比如一個(gè)彈窗組件,最理想的用法是通過(guò)命令式調(diào)用,就像?elementUI?的?this.$message?。而不是在模板中通過(guò)狀態(tài)切換,這種實(shí)現(xiàn)真的很糟糕。
先來(lái)個(gè)最簡(jiǎn)單的例子:
import Vue from 'vue' import Message from './Message.vue'// 構(gòu)造子類 let MessageConstructor = Vue.extend(Message) // 實(shí)例化組件 let messageInstance = new MessageConstructor() // $mount可以傳入選擇器字符串,表示掛載到該選擇器 // 如果不傳入選擇器,將渲染為文檔之外的的元素,你可以想象成 document.createElement()在內(nèi)存中生成dom messageInstance.$mount() // messageInstance.$el獲取的是dom元素 document.body.appendChild(messageInstance.$el)下面實(shí)現(xiàn)一個(gè)簡(jiǎn)易的?message?彈窗組件
Message/index.vue
<template><div class="wrap"><div class="message" :class="item.type" v-for="item in notices" :key="item._name"><div class="content">{{item.content}}</div></div></div> </template> // 默認(rèn)選項(xiàng) const DefaultOptions = {duration: 1500,type: 'info',content: '這是一條提示信息!', } let mid = 0 export default {data() {return {notices: []}},methods: {add(notice = {}) {// name標(biāo)識(shí) 用于移除彈窗l(fā)et _name = this.getName()// 合并選項(xiàng)notice = Object.assign({_name}, DefaultOptions, notice)this.notices.push(notice)setTimeout(() => {this.removeNotice(_name)}, notice.duration)},getName() {return 'msg_' + (mid++)},removeNotice(_name) {let index = this.notices.findIndex(item => item._name === _name)this.notices.splice(index, 1)}} } .wrap {position: fixed;top: 50px;left: 50%;display: flex;flex-direction: column;align-items: center;transform: translateX(-50%); }.message {--borderWidth: 3px;min-width: 240px;max-width: 500px;margin-bottom: 10px;border-radius: 3px;box-shadow: 0 0 8px #ddd;overflow: hidden; }.content {padding: 8px;line-height: 1.3; }.message.info {border-left: var(--borderWidth) solid #909399;background: #F4F4F5; }.message.success {border-left: var(--borderWidth) solid #67C23A;background: #F0F9EB; }.message.error {border-left: var(--borderWidth) solid #F56C6C;background: #FEF0F0; }.message.warning {border-left: var(--borderWidth) solid #E6A23C;background: #FDF6EC; }Message/index.js
import Vue from 'vue' import Index from './index.vue'let messageInstance = null let MessageConstructor = Vue.extend(Index)let init = () => {messageInstance = new MessageConstructor()messageInstance.$mount()document.body.appendChild(messageInstance.$el) }let caller = (options) => {if (!messageInstance) {init(options)}messageInstance.add(options) }export default {// 返回 install 函數(shù) 用于 Vue.use 注冊(cè)install(vue) {vue.prototype.$message = caller} }main.js
import Message from '@/components/Message/index.js'Vue.use(Message)使用
this.$message({type: 'success',content: '成功信息提示',duration: 3000 })總結(jié)