vue中的this.$emit方法
- 使用一:$emit
- 使用二:$emit update 和 .sync 修飾符
作用:用于子組件中觸發父組件方法并傳值
注意:?$emit傳入的事件名稱只能使用小寫,不能使用大寫的駝峰規則命名。
?
使用一:$emit
//子組件中
<template><button @click="handleChildEvent">子組件中觸發的事件</button>
</template><script>
export default {name:'ChildComponent',methods: {handleChildEvent() {// 觸發自定義事件,并傳遞數據給父組件this.$emit('parent-event', 'Hello, World!');}}
}
</script>
//父組件中
<child-component @parent-event="handleParentEvent"/><script>
export default {name: 'ParentComponent',// 注冊子組件components: {ChildComponent}, methods: {handleParentEvent(data) {// 處理自定義事件的邏輯console.log(data); // 輸出:'Hello, World!'}}
}
</script>
使用二:$emit update 和 .sync 修飾符
作用:.sync可以幫我們實現父組件向子組件傳遞的數據的雙向綁定,所以子組件接收到數據后可以直接修改,并且會同時修改父組件的數據
// 父組件
<template>//給子組件傳值時使用.sync修飾符<child :page.sync="page"></child>
</template>
<script>
export default {data(){return {page:1}}
}
</script>
//子組件中
<script>
export default {props:["page"],computed(){// 當我們在子組件里修改 currentPage 時,父組件的 page 也會隨之改變 currentPage {get(){return this.page},set(newVal){//$emit update 修改父組件中的數據this.$emit("update:page", newVal)}}}
}
</script>
相當于省略了父組件給子組件多傳遞一個修改數據的方法
// 帶 .sync 修飾符
<children :selectNode.sync="node" />// 無 .sync 修飾符,等同于
<children :selectNode="node" @update:selectNode="node=$event" />
實現子組件與父組件雙向綁定的【sync】修飾符:其實sync這個修飾符是vue1.0就有的,它可以實現父子組件的雙向綁定,但是Vue2.0被移除了,直到2.3.0版本發布后,又重新開始啟用,由于數據安全問題,后來vue3.x后又被重新取消了。
【.sync】可以很輕松的實現子組件同步修改父組件的值,如果子組件想修改父組件的值,推薦在子組件中以 update:my-prop-name 的模式觸發事件取而代之,也就是這樣:
父組件:
<text-documentv-bind:title="doc.title"v-on:update:title="doc.title = $event"
></text-document>
子組件:
this.$emit("update:title",newTitle)
而上邊的 v-on:update:title="doc.title = $event",本質上就可以用sync這個語法糖來表示,.sync后面緊接的就是父組件中需要被改變的值,看下邊的例子:
父組件:
<template><div><child-com :value.sync="text" ></child-com></div>
</template>
<script>export default{data(){return {text:"父組件的值",}},}
</script>
子組件中修改父組件的值:
<template><div @click="post"></div>
</template>
<script>export default{methods:{post(){this.$emit('update:value',"子組件的值")}}}
</script>