10.(vue3.x+vite)组件间通信方式之props与$emit

40 篇文章 1 订阅 ¥49.90 ¥99.00
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue3中,通过使用v-model实现父子组件的双向数据绑定的方式与Vue2有所不同。在Vue3中,我们可以使用`emit`和`on`来实现父子组件的双向绑定数据。 在父组件中,我们可以通过`v-model`指令绑定一个值,并使用`@update:modelValue`事件和`$emit`方法来更新这个值。在子组件中,我们可以通过`props`接收父组件传递的值,并在需要更新该值的时候使用`$emit`触发`update:modelValue`事件。 以下是一个使用Vue3和TypeScript实现父子组件双向绑定数据的示例: 父组件: ```html <template> <div class="father"> <div class="context"> <h1>这是父组件fatherNum:{{ fatherNum }}</h1> <Son v-model="fatherNum"></Son> </div> </div> </template> <script lang="ts"> import { defineComponent, ref } from 'vue'; import Son from '../components/Son.vue'; export default defineComponent({ components: { Son }, setup() { const fatherNum = ref(0); return { fatherNum }; } }); </script> <style scoped> .father { width: 100vw; height: 100vh; } .context { width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; flex-direction: column; } </style> ``` 子组件: ```html <template> <div class="son"> <button @click="increment">增加</button> <button @click="decrement">减少</button> <p>这是子组件sonNum: {{ modelValue }}</p> </div> </template> <script lang="ts"> import { defineComponent, computed, emit } from 'vue'; export default defineComponent({ props: { modelValue: { type: Number, required: true } }, setup(props, { emit }) { const increment = () => { emit('update:modelValue', props.modelValue + 1); }; const decrement = () => { emit('update:modelValue', props.modelValue - 1); }; return { increment, decrement }; } }); </script> <style scoped> .son { display: flex; } </style> ``` 在这个示例中,父组件中的`fatherNum`通过`v-model`指令与子组件中的`modelValue`进行双向数据绑定。父组件中的值变化时,会触发`update:modelValue`事件,子组件监听该事件并根据需要更新自己的值。 希望对你有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [vue3+vite+ts--组件使用v-model实现双向绑定(vue2&vue3+ts的详细讲解)](https://blog.csdn.net/m0_60893808/article/details/131244155)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GIS之家家长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值