1.元件事件
Parent.Vue中的程式碼
<template>
<h3>Parent</h3>
<br/>
<Child @someEvent="getChildDataHandler"/>
<p>{{ message }}</p>
</template>
<script>
//1.引入元件
import Child from './Child.vue';
export default{
data(){
return{
message:""
}
},
//2.註冊元件
components:{
Child
},
methods:{
getChildDataHandler(data){
console.log("觸發了",data)
this.message=data
}
}
}
</script>
<style scoped></style>
Child.vue中的程式碼:
<template>
<h3>Child</h3>
<button @click="clickEventHandler">傳遞資料給父元素</button>
</template>
<script>
export default{
data(){
return{
name:"zhangsan"
}
},
methods:{
clickEventHandler(){
//觸發父元素中的someEvent事件並把child資料傳遞給這個someEvent事件繫結的方法
this.$emit("someEvent",this.name)
console.log("傳遞資料成功")
}
}
}
</script>
<style scoped></style>
2.元件事件配合v-model使用
Main.Vue程式碼
<template>
<h3>Main</h3>
<Search @searchEvent="searchHandler"/>
<p>{{ message }}</p>
</template>
<script>
import Search from "./SearchComponent.vue"
export default{
data(){
return {
message:""
}
},
components:{
Search
},
methods:{
searchHandler(data){
this.message=data
}
}
}
</script>
Search.vue程式碼
<template>
<input type="text" v-model="search" @input.enter="inputHandler">
</template>
<script>
export default{
data(){
return {
search:"test"
}
},
methods:{
inputHandler(){
this.$emit("searchEvent",this.search)
}
}
}
</script>