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);}} }; <