vue3 父子組件傳值詳解
現(xiàn)在距離vue3的誕生已經(jīng)過了很長(zhǎng)時(shí)間了,筆者也是近期才開始學(xué)習(xí)vue3。對(duì)比vue2來看,vue3在寫法發(fā)生了不小的變化,最典型的例子就是vue3通過ref,或者reactive實(shí)現(xiàn)數(shù)據(jù)的響應(yīng)式。因?yàn)閞ef和reactive的出現(xiàn),使得vue3中父子組件的傳值方式也發(fā)生了變化
咱們先看下vue2中的寫法
父組件:
<!-- 父組件 -->
<template>
<div>
<children :title="title" @getChildren="getChildren"></children>
<div>子組件說: {{ childrenAsk }}</div>
</div>
</template>
<script>
import children from "./children.vue"
export default {
data() {
return {
title: "我是父組件傳過來的值",
childrenAsk: ""
}
},
methods: {
getChildren(val) {
this.childrenAsk = val
}
}
}
</script>
子組件:
<!-- 子組件 -->
<template>
<div>
<div>父組件傳過來的值: {{ title }}</div>
<button @click="askToFather">點(diǎn)擊發(fā)送給父組件</button>
</div>
</template>
<script>
export default {
props: {
title: {
type: String
}
},
data() {
return {
askMsg: "這是我給父組件說的話"
}
},
methods: {
askToFather() {
this.$emit("getChildren", this.askMsg)
}
}
}
</script>
在vue2中,子組件向父組件傳值通過this.$emit的形式實(shí)現(xiàn),但是vue3中,是不存在this的,vue3中將數(shù)據(jù)和函數(shù)都封裝在了setup中,那么vue3是怎么實(shí)現(xiàn)的呢?
我們知道vue3中的setup接收兩個(gè)參數(shù),第一個(gè)參數(shù)是props,即父組件向子組件傳遞的props值,第二個(gè)值為context,這個(gè)值代表了當(dāng)前的上下文對(duì)象,知道這個(gè)東西以后現(xiàn)在來實(shí)現(xiàn)vue3的父子組件傳值
vue3中父?jìng)髯雍蛌ue2中的父?jìng)髯右粯?,再次不做過多闡述,下面重點(diǎn)關(guān)注的是vue3的子傳父
父組件
<template>
<div style="color: aqua">父組件</div>
<div>子組件對(duì)我說:{{ children_msg }}</div>
<children :title="msg" @listen="listenToChildren"></children>
{{ value }}
</template>
<script lang="ts">
import children from "@/views/component_emit/children.vue"
import { defineComponent, ref } from "vue"
export default defineComponent({
components: {
children,
},
name: "father",
setup() {
let msg = "我是父組件"
let children_msg = ref("") // ref的作用是實(shí)現(xiàn)響應(yīng)式, 如果沒有ref則不能實(shí)現(xiàn)響應(yīng)式(引用數(shù)據(jù)類型用reactive)
let listenToChildren = (val) => {
children_msg.value = val // 使用ref包裹的數(shù)據(jù),需要通過.value的形式訪問他的值
}
return {
msg,
children_msg,
listenToChildren,
}
},
})
</script>
<style></style>
子組件:
<template>
<div style="color: brown">子組件</div>
<!-- 父?jìng)髯邮褂梅椒ê蛌ue2相同 -->
<div>父組件傳過來的值為:{{ title }}</div>
<button @click="sayToFather">向父組件說話</button>
</template>
<script lang="ts">
import { defineComponent } from "vue"
export default defineComponent({
name: "children",
props: {
title: {
type: String,
},
},
setup(props, context) {
// context作用是獲取上下文對(duì)象,
// 如果setup寫法為setup(props, { emit })的方式的話,下面的context可以省略
const sayToFather = () => {
const ask = "我是子組件,我對(duì)父組件說話"
context.emit("listen", ask)
}
return {
sayToFather,
}
},
})
</script>
<style></style>
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
簡(jiǎn)單實(shí)現(xiàn)一個(gè)vue公式編輯器組件demo
這篇文章主要介紹了輕松實(shí)現(xiàn)一個(gè)簡(jiǎn)單的vue公式編輯器組件示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01
詳解從Vue.js源碼看異步更新DOM策略及nextTick
本篇文章主要介紹了從Vue.js源碼看異步更新DOM策略及nextTick,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一2017-10-10

