欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3父子組件通信之子組件修改父組件傳過來的值

 更新時(shí)間:2024年05月28日 10:51:06   作者:我愛加班  
這篇文章主要介紹了vue3父子組件通信之子組件修改父組件傳過來的值,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧

一、第一種,通過props方式傳值:

父組件:

父組件調(diào)用子組件Child1時(shí)通過 :msg2= "msg2"把msg2的數(shù)據(jù)傳給子組件,并且通過自定義事件接收子組件的emit通知,用來修改父組件的msg2數(shù)據(jù)。

源碼:

<template>
  <div>
    我是home組件 父組件
    <h1>{{ msg }}</h1>
    <div>父組件--props方式傳值:{{ msg2 }}</div>
    <Child1 :msg2="msg2" @event="eventFn" />
  </div>
</template>
<script setup>
import { ref } from 'vue'
import Child1 from './child1.vue'
const props = defineProps(['msg'])
const msg2 = ref('今天是星期三,多云。')
const eventFn = (val) => {
    msg2.value = val
}
</script>

子組件:

子組件通過defineProps接收一下msg2 ,可以直接展示在模板上,子組件自定義emit事件去通知父組件修改msg2的數(shù)據(jù),數(shù)值是子組件傳過去的。

源碼:

<template>
  <div>
    <h3>大家好,我是子組件1</h3>
    <button @click="handleClick">修改父組件數(shù)據(jù)msg2</button>
    <div>子組件——props方式傳過來:{{ msg2 }}</div>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue'
const props = defineProps(['msg2'])
const emit = defineEmits(['event'])
const handleClick = () => {
    emit('event', '希望早日出太陽,暴富而不是暴曬!')
}
</script>

點(diǎn)擊前:

點(diǎn)擊后:

二、第二種,通過v-model+冒號+要傳的值 的方式(這個(gè)v-model可以寫多個(gè)):

父組件:

父組件調(diào)用子組件時(shí),通過v-model:num="num" 的方式傳值給子組件。

源碼:

<template>
  <div>
    我是home組件 父組件
    <h1>{{ msg }}</h1>
    <div>父組件--props方式傳值:{{ msg2 }}</div>
    <div>父組件num——v-model方式傳值:{{ num }}</div>
    <Child1
     :msg2="msg2" @event="eventFn"
     v-model:num="num"
     />
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import Child1 from './child1.vue'
const props = defineProps(['msg'])
const msg2 = ref('今天是星期三,多云。')
const num = ref(0)
const eventFn = (val) => {
    msg2.value = val
}
</script>

子組件:

子組件也先通過defineProps接收一下num,并展示。然后通過自定義emit事件

const emit = defineEmit(['update: num'])

然后通過點(diǎn)擊事件updateNum方法來觸發(fā)通知父組件修改num數(shù)據(jù)。

源碼:

<template>
  <div>
    <h3>大家好,我是子組件1</h3>
    <button @click="handleClick">修改父組件數(shù)據(jù)msg2</button>
    <div>子組件——props方式傳過來:{{ msg2 }}</div>
    <button @click="updateNum">修改父組件num</button>
    <div>子組件num——v-model方式傳過來:{{ num }}</div>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue'
const props = defineProps(['msg2','num'])
const emit = defineEmits(['event', 'update:num'])
const handleClick = () => {
    emit('event', '希望早日出太陽,暴富而不是暴曬!')
}
const updateNum = () => {
    emit('update:num', 222)
}
</script>

點(diǎn)擊前:

點(diǎn)擊后:

三、父組件調(diào)用子組件時(shí),通過v-model傳多個(gè)值

父組件寫法:

子組件寫法:

效果:

以上就是vue3中,props和v-model兩種常用的父子組件通信方法 。

到此這篇關(guān)于vue3父子組件通信子組件修改父組件傳過來的值的文章就介紹到這了,更多相關(guān)vue3父子組件通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論