vue3父子組件通信之子組件修改父組件傳過來的值
一、第一種,通過props方式傳值:
父組件:
父組件調(diào)用子組件Child1時通過 :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>點擊前:

點擊后:

二、第二種,通過v-model+冒號+要傳的值 的方式(這個v-model可以寫多個):
父組件:
父組件調(diào)用子組件時,通過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'])
然后通過點擊事件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ào)用子組件時,通過v-model傳多個值
父組件寫法:

子組件寫法:

效果:

以上就是vue3中,props和v-model兩種常用的父子組件通信方法 。
到此這篇關于vue3父子組件通信子組件修改父組件傳過來的值的文章就介紹到這了,更多相關vue3父子組件通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue動態(tài)綁定多個class以及帶上三元運算或其他條件
這篇文章主要介紹了vue動態(tài)綁定多個class以及帶上三元運算或其他條件,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
Vue+Element-ui彈窗?this.$alert?is?not?a?function問題
這篇文章主要介紹了Vue+Element-ui彈窗?this.$alert?is?not?a?function問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10
在nuxt使用vueX代替storage的實現(xiàn)方案
這篇文章主要介紹了在nuxt使用vueX代替storage的實現(xiàn)方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10

