我們在進行vue開發時會將公共的部分進行抽象,然后生成一個獨立的組件,這個組件可以被其它頁面參考,如果希望有互動的動作就設計到了值的傳遞,或者方法的回呼等問題,這一次我們主要來說一下父組件和子組件的互動,
值的傳遞
子組件,通過定義了prods,然后可以實作從父組件向子組件的傳遞:
<template>
<div id="app">
這是自定義的組件:{{myMessage}}
<button @click="childClick">呼叫父組件的方法</button>
</div>
</template>
<script>
export default {
name: "testComponent",
props: ["myMessage"],
data() {
return {
message: "hello world",
myNum: 37,
myStr: "lind"
};
},
methods: {
childClick() {
console.log("呼叫childClick");
this.$emit("abcClick", this.myNum, this.myStr);
}
}
};
</script>
父組件/頁面,直接為這個prods賦值即可,注意如果JS里props名稱是小駝峰,在html需要用中線來代替
<testComponent my-message="hello"></testComponent>
<script>
import testComponent from "@/components/testComponent";
export default {
name: "test-grammer",
props: {
//接收父組件傳遞過來的引數
},
components: {
testComponent
}
}
</script>
方法的傳遞/回呼
在父頁面系結子組件的方法,然后子組件在某個時機去觸,這就形成了在子組件里呼叫父組件的方法,使用了$emit來實作
<button @click="childClick">呼叫父組件的方法</button>
<script>
export default {
name: "testComponent",
methods: {
childClick() {
this.$emit("abcClick", this.myNum, this.myStr);
}
}
};
</script>
在父頁面中去系結這個abcClick事件就可以了,當在子組件呼叫這個childClick事件時,系結了abcClick的方法將會被一起回呼
<testComponent @abcClick="sayHello"></testComponent>
<script>
import testComponent from "@/components/testComponent";
export default {
name: "test-grammer",
methods: {
sayHello(Num, Str) {
console.log("hello world~~" + Num + Str);
}
},
};
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/55597.html
標籤:JavaScript
