FreezeJ' Blog

Vue3父子组件传递变量

2026-01-27

通过defineModelv-model结合可以大大精简代码。
注意:defineModel仅在 3.4+ 中可用
参考文档:https://cn.vuejs.org/guide/components/v-model

原始写法

【父组件】

<script setup lang="ts">
    import Counter from '../components/Counter.vue'
    import { ref } from 'vue';
    const count = ref(0);
</script>

<template>
    <div>
        <h3>计数器</h3>
        <label>请输入一个数字:<input type="number" v-model="count" /></label>
        <Counter :count="count" @update:count="count = $event" />
    </div>
</template>

【子组件】

<script setup lang="ts">

const props = defineProps({
    count: {
        type: Number,
        default: 0
    }
})

const emit = defineEmits(['update:count'])

const increment = () => {
  emit('update:count', props.count + 1)
}

const decrement = () => {
  emit('update:count', props.count - 1)
}

const clear = () => {
  emit('update:count', 0)
}
</script>

<template>
  <div>
    <button @click="clear">清零</button>
    <button @click="increment">增加</button>
    <button @click="decrement">减少</button>
  </div>
</template>

精简写法

【父组件】

<script setup lang="ts">
    import Counter from '../components/Counter.vue'
    import { ref } from 'vue';
    const count = ref(0);
</script>

<template>
    <div>
        <h3>计数器</h3>
        <label>请输入一个数字:<input type="number" v-model="count" /></label>
        <Counter v-model:count="count" />
    </div>
</template>

【子组件】

<script setup lang="ts">
const count = defineModel<number>('count', { default: 0 })
</script>

<template>
  <div>
    <button @click="count = 0">清零</button>
    <button @click="count++">增加</button>
    <button @click="count--">减少</button>
  </div>
</template>
使用支付宝打赏
使用微信打赏

若你觉得我的文章对你有帮助,欢迎点击上方按钮对我打赏