[01] props.sync


Posted by m6fish on 2020-12-25

Photo by carolyn christine on Unsplash

前言

第一篇文章的內容就沒有出現在vue-pattern內XD
收錄這篇文章的原因,是因為這個語法自己沒用過,然後某次面試的時候被問到答不出來(汗
回來之後立馬查了一下,他其實是語法糖,所以習慣使用原生語法後就忘了有這東西可惡坑我

主題

props.sync = props + v-on事件

同前言提到的,他是一個把父組件內傳遞propsv-on事件,二合一的語法糖,用以達到子組件可以改變父組件成員變數的值(像是'sync'[同步]的效果)。同時也因為是語法糖,所以綁定的事件名稱會固定是 update:${props}

// index.vue 父層
<div>
    <button @click="addCount" >ADD by parent</button>
    <childA :count="count" @counter-update="addCount" :score.sync="score"/>
</div>

這邊的 score.sync 會拆成 v-bind={score:score} 再加上 @update:score="score = $event"
注: 旁邊的 @counter-update只是對照組,即自訂事件也可以達到同樣的效果

// childA.vue 子層
<div>
    <p>Count:{{count}}</p>
    <button @click="childClick">Add by childA</button>

    <p>Score:{{score}}</p>
    <button @click="scoreClick">Calculate Score</button>
</div>
methods: {
    childClick () {
        console.log('click by childA')
        this.$emit('counter-update', this.count + 1)
    },
    scoreClick () {
        console.log('click by childA-score')
        this.$emit('update:score', this.count * 10)
    }
}

子層大致沒有影響,一樣透過$emit去影響父層,但是$emit的名稱會是update:score

總結

試想了一下,props.sync語法糖其實跟v-module有點像,都可以直接套用在簡單情境上,減少頁面上的code。但複雜狀況還是直接使用原來的比較靈活。


#Vue #vue-pattern







Related Posts

CSS保健室|opacity

CSS保健室|opacity

AI輔導室|靈活運用鏡射工具

AI輔導室|靈活運用鏡射工具

Vue.js 學習旅程Mile 13 – List Rendering 列表渲染篇:v-for

Vue.js 學習旅程Mile 13 – List Rendering 列表渲染篇:v-for


Comments