一、父组件给子组件传值
父组件中:
<template>
<div>
<ChildComponent :message="message" :count="count" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
message: 'Hello',
count: 10
};
}
};
</script>
子组件中:
<template>
<div>
<p>{{ message }}</p>
<p>{{ count }}</p>
</div>
</template>
<script>
export default {
props: {
message: String,
count: Number
}
};
</script>
二、子组件给父组件传值
父组件中:
<template>
<div>
<ChildComponent @childEvent="handleChildData" />
<p>Received data from child: {{ childData }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
childData: ''
};
},
methods: {
handleChildData(data) {
this.childData = data;
}
}
};
</script>
子组件中:
<template>
<div>
<button @click="sendDataToParent">Send Data to Parent</button>
</div>
</template>
<script>
export default {
methods: {
sendDataToParent() {
const data = 'Hello from child';
this.$emit('childEvent', data);
}
}
};
</script>