1. 父組件向子組件傳值(props)
-
父組件代碼:Parent.vue
<template><div><h2>父組件</h2><Child :parent-msg="parentMsg" /></div> </template><script> import Child from './Child.vue';export default {components: {Child},data() {return {parentMsg: '這是父組件傳遞的消息'};} }; </script>
-
子組件代碼:Child.vue
<template><div><h3>子組件</h3><p>從父組件接收到的消息:{{ parentMsg }}</p></div> </template><script> export default {props: {parentMsg: {type: String,required: true}} }; </script>
2. 子組件向父組件傳值(this.$emit)
-
子組件代碼:Child.vue
<template><div><h3>子組件</h3><button @click="sendMessage">向父組件發送消息</button></div> </template><script> export default {data() {return {childMsg: '這是子組件的消息'};},methods: {sendMessage() {this.$emit('sendMessage', this.childMsg);}} }; <