做爲一位Vue工程師,這些開發技巧你都會嗎?

路由參數解耦

通常在組件內使用路由參數,大多數人會這樣作:css

export default {
    methods: {
        getParamsId() {
            return this.$route.params.id
        }
    }
}

在組件中使用 $route 會使之與其對應路由造成高度耦合,從而使組件只能在某些特定的 URL 上使用,限制了其靈活性。html

正確的作法是經過 props 解耦vue

const router = new VueRouter({
    routes: [{
        path: '/user/:id',
        component: User,
        props: true
    }]
})

將路由的 props 屬性設置爲 true 後,組件內可經過 props 接收到 params 參數api

export default {
    props: ['id'],
    methods: {
        getParamsId() {
            return this.id
        }
    }
}

另外你還能夠經過函數模式來返回 props數組

const router = new VueRouter({
    routes: [{
        path: '/user/:id',
        component: User,
        props: (route) => ({
            id: route.query.id
        })
    }]
})

文檔:https://router.vuejs.org/zh/guide/essentials/passing-props.htmlapp

函數式組件

函數式組件是無狀態,它沒法實例化,沒有任何的生命週期和方法。建立函數式組件也很簡單,只須要在模板添加 functional 聲明便可。通常適合只依賴於外部數據的變化而變化的組件,因其輕量,渲染性能也會有所提升。dom

組件須要的一切都是經過 context 參數傳遞。它是一個上下文對象,具體屬性查看文檔。這裏 props 是一個包含全部綁定屬性的對象。ide

函數式組件函數

<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: ''
        }
    }
}

文檔:https://cn.vuejs.org/v2/guide/render-function.html#%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BB%84%E4%BB%B6

樣式穿透

在開發中修改第三方組件樣式是很常見,但因爲 scoped 屬性的樣式隔離,可能須要去除 scoped 或是另起一個 style 。這些作法都會帶來反作用(組件樣式污染、不夠優雅),樣式穿透在css預處理器中使用才生效。

咱們可使用 >>>/deep/ 解決這一問題:

<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高階使用

當即執行

watch 是在監聽屬性改變時纔會觸發,有些時候,咱們但願在組件建立後 watch 可以當即執行

可能想到的的方法就是在 create 生命週期中調用一次,但這樣的寫法不優雅,或許咱們可使用這樣的方法

export default {
    data() {
        return {
            name: 'Joe'
        }
    },
    watch: {
        name: {
            handler: 'sayName',
            immediate: true
        }
    },
    methods: {
        sayName() {
            console.log(this.name)
        }
    }
}

深度監聽

在監聽對象時,對象內部的屬性被改變時沒法觸發 watch ,咱們能夠爲其設置深度監聽

export default {
    data: {
        studen: {
            name: 'Joe',
            skill: {
                run: {
                    speed: 'fast'
                }
            }
        }
    },
    watch: {
        studen: {
            handler: 'sayName',
            deep: true
        }
    },
    methods: {
        sayName() {
            console.log(this.studen)
        }
    }
}

觸發監聽執行多個方法

使用數組能夠設置多項,形式包括字符串、函數、對象

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)
        }
    }
}

文檔:https://cn.vuejs.org/v2/api/#watch

watch監聽多個變量

watch自己沒法監聽多個變量。但咱們能夠將須要監聽的多個變量經過計算屬性返回對象,再監聽這個對象來實現「監聽多個變量」

export default {
    data() {
        return {
            msg1: 'apple',
            msg2: 'banana'
        }
    },
    compouted: {
        msgObj() {
            const { msg1, msg2 } = this
            return {
                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
        }
    }
}

事件參數$event

$event 是事件對象的特殊變量,在一些場景能給咱們實現複雜功能提供更多可用的參數

原生事件

在原生事件中表現和默認的事件對象相同

<template>
    <div>
        <input type="text" @input="inputHandler('hello', $event)" />
    </div>
</template>
export default {
    methods: {
        inputHandler(msg, e) {
            console.log(e.target.value)
        }
    }
}

自定義事件

在自定義事件中表現爲捕獲從子組件拋出的值

my-item.vue :

export default {
    methods: {
        customEvent() {
            this.$emit('custom-event', 'some value')
        }
    }
}

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'
        }
    }
}

文檔:https://cn.vuejs.org/v2/guide/events.html#%E5%86%85%E8%81%94%E5%A4%84%E7%90%86%E5%99%A8%E4%B8%AD%E7%9A%84%E6%96%B9%E6%B3%95

https://cn.vuejs.org/v2/guide/components.html#%E4%BD%BF%E7%94%A8%E4%BA%8B%E4%BB%B6%E6%8A%9B%E5%87%BA%E4%B8%80%E4%B8%AA%E5%80%BC

自定義組件雙向綁定

組件 model 選項:

容許一個自定義組件在使用 v-model 時定製 prop 和 event。默認狀況下,一個組件上的 v-model 會把 value 用做 prop 且把 input 用做 event,可是一些輸入類型好比單選框和複選框按鈕可能想使用 value prop 來達到不一樣的目的。使用 model 選項能夠迴避這些狀況產生的衝突。

input 默認做爲雙向綁定的更新事件,經過 $emit 能夠更新綁定的值

<my-switch v-model="val"></my-switch>
export default {
    props: {
        value: {
            type: Boolean,
            default: false
        }
    },
    methods: {
        switchChange(val) {
            this.$emit('input', val)
        }
    }
}

修改組件的 model 選項,自定義綁定的變量和事件

<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', num++)
        }
    }
}

文檔:https://cn.vuejs.org/v2/api/#model

監聽組件生命週期

一般咱們監聽組件生命週期會使用 $emit ,父組件接收事件來進行通知

子組件

export default {
    mounted() {
        this.$emit('listenMounted')
    }
}

父組件

<template>
    <div>
        <List @listenMounted="listenMounted" />
    </div>
</template>

其實還有一種簡潔的方法,使用 @hook 便可監聽組件生命週期,組件內無需作任何改變。一樣的, createdupdated 等也可使用此方法。

<template>
    <List @hook:mounted="listenMounted" />
</template>

程序化的事件偵聽器

好比,在頁面掛載時定義計時器,須要在頁面銷燬時清除定時器。這看起來沒什麼問題。但仔細一看 this.timer 惟一的做用只是爲了可以在 beforeDestroy 內取到計時器序號,除此以外沒有任何用處。

export default {
    mounted() {
        this.timer = setInterval(() => {
            console.log(Date.now())
        }, 1000)
    },
    beforeDestroy() {
        clearInterval(this.timer)
    }
}

若是能夠的話最好只有生命週期鉤子能夠訪問到它。這並不算嚴重的問題,可是它能夠被視爲雜物。

咱們能夠經過 $on$once 監聽頁面生命週期銷燬來解決這個問題:

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)
        })
    }
}

使用這個方法後,即便咱們同時建立多個計時器,也不影響效果。由於它們會在頁面銷燬後程序化的自主清除。

文檔:https://cn.vuejs.org/v2/guide/components-edge-cases.html#%E7%A8%8B%E5%BA%8F%E5%8C%96%E7%9A%84%E4%BA%8B%E4%BB%B6%E4%BE%A6%E5%90%AC%E5%99%A8

手動掛載組件

在一些需求中,手動掛載組件可以讓咱們實現起來更加優雅。好比一個彈窗組件,最理想的用法是經過命令式調用,就像 elementUIthis.$message 。而不是在模板中經過狀態切換,這種實現真的很糟糕。

先來個最簡單的例子:

import Vue from 'vue'
import Message from './Message.vue'

// 構造子類
let MessageConstructor = Vue.extend(Message)
// 實例化組件
let messageInstance = new MessageConstructor()
// $mount能夠傳入選擇器字符串,表示掛載到該選擇器
// 若是不傳入選擇器,將渲染爲文檔以外的的元素,你能夠想象成 document.createElement()在內存中生成dom
messageInstance.$mount()
// messageInstance.$el獲取的是dom元素
document.body.appendChild(messageInstance.$el)

下面實現一個簡易的 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>
// 默認選項
const DefaultOptions = {
    duration: 1500,
    type: 'info',
    content: '這是一條提示信息!',
}
let mid = 0
export default {
    data() {
        return {
            notices: []
        }
    },
    methods: {
        add(notice = {}) {
            // name標識 用於移除彈窗
            let _name = this.getName()
            // 合併選項
            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 函數 用於 Vue.use 註冊
    install(vue) {
        vue.prototype.$message = caller
    }
}

main.js

import Message from '@/components/Message/index.js'

Vue.use(Message)

使用

this.$messagae({
    type: 'success',
    content: '成功信息提示',
    duration: 3000
})

文檔:https://cn.vuejs.org/v2/api/#vm-mount

相關文章
相關標籤/搜索