vue2父组件获取子组件的值
时间: 2023-09-14 14:09:55 浏览: 54
在Vue.js 2中,父组件可以通过子组件的引用来获取子组件的值。下面是一个示例:
在子组件中,你可以通过$emit方法触发一个自定义事件,并将需要传递给父组件的值作为参数:
```html
<template>
<div>
<button @click="sendValueToParent">Send Value to Parent</button>
</div>
</template>
<script>
export default {
methods: {
sendValueToParent() {
this.$emit('childValue', 'Hello from child');
}
}
}
</script>
```
在父组件中,你可以使用v-on指令监听子组件触发的自定义事件,并在相应的方法中接收子组件传递的值:
```html
<template>
<div>
<child-component @childValue="getValueFromChild"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
getValueFromChild(value) {
console.log(value); // 输出 'Hello from child'
}
}
}
</script>
```
通过这种方式,你可以在父组件中获取子组件传递的值。