不知道小伙伴們還記不記得在用 Vue 構建 TodoList 案例的博客中,我們有涉及到要從子組件中把資料傳遞給父組件,當時我用的方法是,讓父組件給子組件傳遞一個函式,然后子組件把要傳過來的資料放在那個函式中,這樣父組件就可以拿到資料了,當然方法不止這一種,這不,博主又學到新方法了,迫不及待給你們分享,
一種組件間通信的方式,適用于:子組件 ===> 父組件
使用場景:A 是父組件,B 是子組件,B 想給 A 傳資料,那么就要在 A 中給 B 系結自定義事件(事件的回呼在 A 中)
組件自定義事件_系結:
第一種方式:
在父組件中:
<Student @getDate="getStudentName" /> 或 <Student v-on:getDate="getStudentName"/>
在父組件中通過 @ 或 v-on 方式給要提交資料的組件(即這里的 Student 組件)系結一個名 getDate 的自定義事件,當這個自定義事件被觸發的時候就會執行 getStudentName 方法,該方法定義在父組件中,子組件觸發該 getDate 自定義事件的方式是:this.$emit("getDate", 資料) 通過 $emit 方式,第一個引數是要觸發的事件名,第二個引數是要傳過去的資料,當然后面還可以繼續寫多個資料,都會被一并傳過去
App.vue(父組件)
<template>
<div class="box">
<!-- 通過父組件給子組件系結一個自定義事件實作:子給父傳遞資料(第一種寫法,使用 @ 或 v-on) -->
<Student v-on:getDate="getStudentName"></Student>
</div>
</template>
<script>
//引入 Student 組件
import Student from "./components/Student";
export default {
name: "App",
},
components: {
Student,
},
methods: {
getStudentName(value, ...a) {
//把除第一個資料之外的,其余資料以陣列的形式放到 a 中
console.log("我拿到了學生的名字", value, a);
},
},
};
</script>
<style>
/*base*/
.box {
background: #ccc;
}
</style>
Student.vue(子組件)
<template>
<div class="student">
<h1>{{ msg }}</h1>
<h2>學生姓名: {{ myName }}</h2>
<h2>學生性別: {{ mySex }}</h2>
<button @click="sendStudentName">點我提交資料</button>
<!--通過點擊事件,觸發 sendStudentName 方法-->
</div>
</template>
<script>
export default {
name: "Student",
data() {
return {
msg: "我是一個大三的學生",
myName: "張三",
mySex: "男",
};
},
methods: {
sendStudentName() {
// 在該方法中通過原型物件觸發 getDate 自定義事件,傳入多個資料
this.$emit("getDate", this.myName, 6666,87778);
},
},
};
</script>
<style lang="less" scoped>
.student {
border: 2px solid pink;
}
</style>
第二種方式:
在父組件中:
<Student ref="demo" /> ......
mounted(){
this.$refs.demo.$on('getDate',this.getStudentName)
}
這種方式,通過 ref 來獲取到 Student 的組件實體物件,并將其放到 demo 中,要使用的時候通過 this.$refs.demo ,列印輸出來的就是 Student 的組件實體物件,然后我們在其上面系結一個自定義事件 getDate,當這個事件觸發的時候,就呼叫后面的方法(如果該方法在父組件中定義好了,那就通過 this.xxx 來獲取,或者直接將其寫成箭頭函式) ,觸發該事件的方法寫在子組件中,跟方法一同理,this.$emit("getDate", 資料)
App.vue(父組件)
<template>
<div class="box">
<!-- 通過父組件給子組件系結一個自定義事件實作:子給父傳遞資料(第二種寫法,使用 ref) -->
<Student ref="demo" />
</div>
</template>
<script>
import Student from "./components/Student";
export default {
name: "App",
components: {
Student,
},
methods: {
getStudentName(value, ...a) {
console.log("我拿到了學生的名字", value, a);
},
},
mounted() {
setTimeout(() => {
//通過獲取到 student 組件給它系結一個 getDate 事件,當觸發這個事件的時候呼叫 getStudentName 方法
this.$refs.demo.$on("getDate", this.getStudentName);
// 讓這個方法只執行一次
// this.$refs.demo.$once("getDate", this.getStudentName);
}, 3000);
},
};
</script>
<style>
/*base*/
.box {
background: #ccc;
}
</style>
(Student 子組件中的代碼和方法一中的一樣,所以這里就不再放了)
其中若想讓自定義事件只能觸發一次,可以使用 once 修飾符,或 $once 方法
方法二與方法一相比,雖然方法二代碼要多一些,但是靈活性也更高,因為它可以配合定時器使用,實作延遲幾秒后再系結
組件自定義事件_解綁:
this.$off('demo') //解綁一個自定義事件
this.$off(['demo1','demo2']) //解綁多個自定義事件
this.$off(); //解綁全部事件

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/378221.html
標籤:其他
上一篇:JS 實作兩數之和
下一篇:和Ajax斗志斗勇的日子
