Vue3兄弟组件之间的怎么进行数据传递给出示例代码
时间: 2023-06-04 22:04:44 浏览: 191
好的,关于Vue3兄弟组件之间的数据传递,可以通过props、$emit、provide/inject等方式进行。以下是一个简单的示例代码:
//组件A
<template>
<div>
<h2>组件A</h2>
<p>当前计数:{{count}}</p>
<button @click="increaseCount">增加计数</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
},
methods: {
increaseCount() {
this.count++
this.$emit('countChange', this.count)
}
}
}
</script>
//组件B
<template>
<div>
<h2>组件B</h2>
<p>来自组件A的计数:{{externalCount}}</p>
</div>
</template>
<script>
export default {
props: {
externalCount: Number
}
}
</script>
// 父组件
<template>
<div>
<component-a @countChange="handleCountChange" />
<component-b :externalCount="currentCount" />
</div>
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
components: {
ComponentA,
ComponentB
},
data() {
return {
currentCount: 0
}
},
methods: {
handleCountChange(count) {
this.currentCount = count
}
}
}
</script>
阅读全文