Vue中如何从页面向template-main组件传递消息修改其变量
解决方案
你之前的方案无效是因为搞反了事件传递方向,且监听位置错误。下面分两种场景给出正确实现方式:
场景1:页面(父组件)主动向template-main(子组件)传值修改内部变量
父组件向子组件传值应该用props,配合watch监听props变化来同步内部变量:
- 修改template-main组件的脚本:
export default { props: { // 定义接收的props syncMessage: { type: String, default: '' } }, data() { return { innerVariable: '' // 需要修改的内部变量 } }, watch: { // 监听props变化,同步到内部变量 syncMessage(newVal) { this.innerVariable = newVal; } } }
- 在页面中通过props传递值:
<template> <template-main :sync-message="pageMsg"> ...页面代码... </template-main> </template> <script> export default { data() { return { pageMsg: '' } }, methods: { sendMsg() { this.pageMsg = 'hello'; // 修改pageMsg,自动同步到template-main的内部变量 } } } </script>
如果需要双向绑定,也可以用Vue的v-model语法糖简化:
template-main组件:
export default { props: { modelValue: { type: String, default: '' } }, emits: ['update:modelValue'], data() { return { innerVariable: this.modelValue } }, watch: { innerVariable(newVal) { this.$emit('update:modelValue', newVal); }, modelValue(newVal) { this.innerVariable = newVal; } } }
页面中使用:
<template> <template-main v-model="pageMsg"> ...页面代码... </template-main> </template> <script> export default { data() { return { pageMsg: '' } }, methods: { sendMsg() { this.pageMsg = 'hello'; } } } </script>
场景2:页面中slot内的内容向template-main组件传值
如果是slot里的按钮、子组件要通知template-main修改变量,不能在slot标签上监听事件,应该在template-main组件本身上绑定事件监听:
- 修改template-main组件:
<template> <div> ... <slot></slot> ... </div> </template> <script> export default { data() { return { innerVariable: '' } }, methods: { handleMensagemRecebida(msg) { this.innerVariable = msg; } } } </script>
- 在页面中绑定事件并触发:
<template> <!-- 在template-main组件上绑定事件监听 --> <template-main @message-to-template="handleMensagemRecebida"> <!-- slot内的内容触发事件 --> <button @click="sendMsg">发送消息</button> </template-main> </template> <script> export default { methods: { sendMsg() { this.$emit('message-to-template', 'hello'); } } } </script>
内容的提问来源于stack exchange,提问作者aguiadouro
相关产品推荐
相关产品推荐

