vue3 父子組件傳值詳解
現(xiàn)在距離vue3的誕生已經(jīng)過了很長時間了,筆者也是近期才開始學習vue3。對比vue2來看,vue3在寫法發(fā)生了不小的變化,最典型的例子就是vue3通過ref,或者reactive實現(xiàn)數(shù)據(jù)的響應式。因為ref和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">點擊發(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的形式實現(xiàn),但是vue3中,是不存在this的,vue3中將數(shù)據(jù)和函數(shù)都封裝在了setup中,那么vue3是怎么實現(xiàn)的呢?
我們知道vue3中的setup接收兩個參數(shù),第一個參數(shù)是props,即父組件向子組件傳遞的props值,第二個值為context,這個值代表了當前的上下文對象,知道這個東西以后現(xiàn)在來實現(xiàn)vue3的父子組件傳值
vue3中父傳子和vue2中的父傳子一樣,再次不做過多闡述,下面重點關注的是vue3的子傳父
父組件
<template>
<div style="color: aqua">父組件</div>
<div>子組件對我說:{{ 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的作用是實現(xiàn)響應式, 如果沒有ref則不能實現(xiàn)響應式(引用數(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>
<!-- 父傳子使用方法和vue2相同 -->
<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作用是獲取上下文對象,
// 如果setup寫法為setup(props, { emit })的方式的話,下面的context可以省略
const sayToFather = () => {
const ask = "我是子組件,我對父組件說話"
context.emit("listen", ask)
}
return {
sayToFather,
}
},
})
</script>
<style></style>
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內(nèi)容!
相關文章
詳解從Vue.js源碼看異步更新DOM策略及nextTick
本篇文章主要介紹了從Vue.js源碼看異步更新DOM策略及nextTick,具有一定的參考價值,感興趣的小伙伴們可以參考一2017-10-10

