父组件通过 props 向下传递数据给子组件,子组件通过 events 向上给父组件发送消息。
父组件:
<div><div style="background:#34495E;color: #fff; padding:20px"><p style="margin-bottom: 20px">这是父组件</p><div style="background:#E74C3C;color: #fff; padding:20px; margin-top:20px"><p>接受来自子组件的内容: </p><p style="margin-top:20px;background:#fff; color:#000; padding:5px; line-height:1.5;">{{hello}}</p></div></div><div style="background:#34495E;color: #fff; padding:20px; margin-top:20px"><p style="margin-bottom: 20px">这是子组件</p><musicsearch @trans="transContent" :pupu="hello" :info="info"></musicsearch></div></div>
export default {components: {musicsearch},data() {return {hello: '',info: ''}},methods: {transContent(msgs) {this.hello = msgs;this.info = msgs;}}
}
子组件:
<div><div style="margin-top:20px; background:#E74C3C; padding:10px;"><input type="text" ref="ipt" style="border:none; margin-top:10px; margin-bottom: 20px; border-radius:4px; width:90%; height:18px; padding:5px; line-height:18px; border:1px solid #fff"><button @click="sendVal()" style="margin-bottom: 20px; border:none; outline:none; border-radius:4px; height:28px; line-height:28px; background:#F1C40F; color:#fff;">向父组件发送内容按钮</button></div><div style="margin-top:20px; background:#E74C3C; padding:10px;"><button @click="click()" style=" margin-top:10px; border:none; outline:none; border-radius:4px; height:28px; line-height:28px; background:#F1C40F; color:#fff;">接受来自父组件的内容按钮</button><div style="margin-top:20px;background:#fff; color:#000; padding:5px; line-height:1.5;">{{msg}}</div></div></div>export default {name: 'girl-group',props: {info: ''},data() {return {msg: ''}},methods: {sendVal() {this.$emit('trans', this.$refs.ipt.value);//这里在父组件使用v-on来监听子组件上的自定义事件($emit的变化),一旦发生变化click方法里的值就会跟着改变,调用click事件可看到信息},click() {this.msg = this.info;}}
}