Vue中如何将子组件的输入值传递给根实例?
问题分析与解决方案
原实现的问题
你的现有思路不可行,代码存在多处逻辑错误,直接导致输出undefined:
- 根实例定义
props: ['handle']是完全错误的用法:props是父组件向子组件传递数据的接口,根实例作为顶层组件没有上层父组件为它传递handle属性,自然读取到undefined,这是控制台输出异常的直接原因。 - 没有建立根实例与子组件实例的关联:你没有在根实例模板中使用
custom-form组件,也没有通过ref标记子组件实例,根本无法访问到子组件的属性或方法。 - 子组件的
inputValue计算属性语法错误:get方法没有加return,get(){ this.title }要改为get(){ return this.title }才能正常返回值。 - 根实例的
components选项格式错误:Vue的components选项是对象格式,不是数组,且你已经通过app.component全局注册了子组件,根实例不需要重复注册即可使用。 - 生命周期选择错误:就算你用
ref标记了子组件,created生命周期执行时子组件还未挂载,无法获取到子组件实例,需要在mounted生命周期中操作。
正确实现方式
方案1:通过ref直接访问子组件实例(符合你最初的思路)
如果你就是需要从根实例直接读取子组件的属性/方法,可以用ref实现,修正后代码如下:
var app = Vue.createApp({ template: `<custom-form ref="formRef" />`, methods: { showData() { // 通过$refs获取子组件实例,调用子组件方法/读取属性 console.log(this.$refs.formRef.title) return this.$refs.formRef.handle() } }, mounted() { // 必须在mounted及之后的生命周期操作,子组件才完成挂载 console.log(this.showData()) } }) app.component('custom-form', { props: ['value'], template: ` <h1>{{title}}</h1> <input type="text" v-model="inputValue" /> `, data() { return { title: 'login' } }, computed: { inputValue: { get() { // 补全return return this.title }, set(v) { this.$emit('update:inputValue',v) } } }, methods: { handle() { return this.inputValue } } }) app.mount('#app')
方案2:通过emit事件传递数据(更符合Vue单向数据流规范,推荐)
常规的子组件向父组件传递数据的方式是子组件emit事件,父组件监听事件接收数据,耦合度更低:
var app = Vue.createApp({ template: `<custom-form @update:inputValue="handleChildValue" />`, methods: { handleChildValue(val) { // 接收子组件传递过来的值 console.log('子组件传来的值:', val) } } }) // 子组件代码基本不变,input值变化时会自动emit事件 app.component('custom-form', { props: ['value'], template: ` <h1>{{title}}</h1> <input type="text" v-model="inputValue" /> `, data() { return { title: 'login' } }, computed: { inputValue: { get() { return this.title }, set(v) { this.$emit('update:inputValue',v) } } } }) app.mount('#app')
内容的提问来源于stack exchange,提问作者v01d
相关产品推荐
相关产品推荐

