#vue3的踩坑记录【一】
vue3 setup语法糖中父组件调用子组件方法或属性
父组件:
<script setup>
import hello from './components/HelloWorld.vue';
import {
ref,
} from "vue"
let a = ref(1)
let re = ref(null)
let add = () => {
a.value += 1;
re.value.add2()
}
</script>
<template>
<hello ref="re"></hello>
<div>
<button @click="add">+</button>
</div>
</template>
子组件:
<script setup>
import {
ref
} from 'vue'
const count = ref(0)
function add2() {
count.value += 2;
}
defineExpose({
add2
})
</script>
<template>
<p>{{count}}</p>
</template>
关键:需要通过defineExpose方法将子组件方法或属性暴露出来,不然没法调用
具体解释请看官方文档