一.父组件获取子组件的值
父组件获取子组件的值有两种方式,第一种是使用ref;第二种是
使用$emit
事件
1.使用ref
可以通过ref
属性来引用子组件,并访问其数据或方法。
子组件(ChildComponent.vue):
<template>
<div>
<input v-model="value" />
</div>
</template>
<script>
export default {
data() {
return {
value: ''
};
}
}
</script>
父组件:
<template>
<div>
<ChildComponent ref="childRef" />
<button @click="getValue">获取值</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
getValue() {
const child = this.$refs.childRef;
console.log(child.value); // 访问子组件的data属性
}
}
}
</script>
2.使用$emit
事件
子组件主动通知父组件其值的变化。
子组件(ChildComponent.vue):
<template>
<div>
<input v-model="value" @input="notifyParent" />
</div>
</template>
<script>
export default {
data() {
return {
value: ''
};
},
methods: {
notifyParent() {
this.$emit('update:value', this.value);
}
}
}
</script>
父组件:
<template>
<div>
<ChildComponent @update:value="handleValueUpdate" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleValueUpdate(value) {
console.log(value); // 接收子组件传递的值
}
}
}
</script>
二.子组件获取父组件的值
子组件获取父组件的值通常有两种方法,一种是使用props,一种是
使用$emit
和事件监听(父子通信)。
1.使用props
通过在子组件中定义props
来接收父组件传递的值。
父组件 (ParentComponent.vue
):
<template>
<div>
<ChildComponent :parentValue="parentValue" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentValue: '这是从父组件传递的值'
};
}
}
</script>
子组件 (ChildComponent.vue
):
<template>
<div>
<p>{
{ parentValue }}</p>
</div>
</template>
<script>
export default {
props: ['parentValue']
}
</script>
2. 使用$emit
和事件监听(父子通信)
如果子组件需要更新父组件的值,可以使用$emit
在子组件中触发一个事件,然后在父组件中监听这个事件。
子组件 (ChildComponent.vue
):
<template>
<button @click="updateParent">更新父组件的值</button>
</template>
<script>
export default {
methods: {
updateParent() {
this.$emit('update-value', '新的值');
}
}
}
</script>
父组件 (ParentComponent.vue
):
<template>
<div>
<ChildComponent @update-value="handleUpdate" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentValue: '这是从父组件传递的值'
};
},
methods: {
handleUpdate(newValue) {
this.parentValue = newValue;
}
}
}
</script>