vue3 子组件 修改 父组件值

5,371 阅读1分钟

vue3 已使用 v-model 的形式代替 sync, 进行 子组件 修改 父组件值

//父组件
<template> 
   <Children v-model:count="count" /> 
</template> 
<script setup lang="ts"> 
   import { ref } from 'vue'; 
   import Children from './components/Children.vue' 
   const count = ref<number>(0) 
</script>
//子组件 Children
<template> 
    <h1>{{ count }}</h1> 
    <button @click="addCount">点击改变父组件的值</button> 
</template> 
<script setup lang="ts"> 
    import { ref, defineProps, reactive, onMounted, watch } from 'vue' 
    const props = defineProps({ 
        count: { type: Number, required: true }
    }) 
    const emit = defineEmits(['update:count']) 
    const addCount:() => void = () => { 
        emit('update:count', props.count + 1) 
    } 
</script>