vue3.0父子傳參,子修改父數(shù)據(jù)的實現(xiàn)
更新時間:2022年04月29日 10:43:13 作者:鬧鬧沒有鬧
這篇文章主要介紹了vue3.0父子傳參,子修改父數(shù)據(jù)的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
父子傳參,子修改父數(shù)據(jù)
父組件
父親傳值給兒子,兒子可以修改父親的數(shù)據(jù)(同步)
<template> ? <div> ? ? 父組件 ? ? {{ data }} ? ? <button @click="add()">修改</button> ? ? <hr /> ? ? 子組件:<Son /> ? </div> </template>
<script> import Son from "./components/Son.vue"; import { provide, ref, shallowRef ,readonly,shallowReadonly} from "vue"; export default { ? components: { ? ? Son, ? }, ? setup() { ? ? let data = ref("123"); ? ? let updata = () => { ? ? ? data += "=="; ? ? }; ? ? let add = ()=>{ ? ? ? data+="=12" ? ? } ? ? provide("updata",updata); ? ? provide("show", data); ? ? return { ? ? ? data, ? ? ? updata, ? ? ? add ? ? }; ? }, }; </script> <style lang="less" scoped></style>
子組件
<template> ? <div>{{son}}</div> ? <button @click="updataSon(12)">更改</button> </template>
<script> import { ref,inject } from "vue"; export default { ? setup() { ? ? const son = (inject("show")); ? ? const updataSon = inject("updata") ? ? return{ ? ? ? ? son, ? ? ? ? updataSon ? ? } ? }, }; </script> <style lang="less" scoped></style>
父子組件傳值(語法糖)
父子組件交互
<template> ? ? <el-icon :size="size" :color="color" @click="change"> ? ? ? ? <component :is="name"></component> ? ? </el-icon> </template>
<script setup> import { defineProps, defineEmits, defineExpose} from 'vue' // 定義傳值類型 const props = defineProps({ ? ? name: { ? ? ? ? type: String, ? ? ? ? required: true, ? ? }, ? ? size: { ? ? ? ? type: String, ? ? ? ? default: '', ? ? }, ? ? color: { ? ? ? ? type: String, ? ? ? ? default: '', ? ? }, }) // 定義事件名 const emit = defineEmits(['change'])? // 觸發(fā)事件 const change =()=>{ ? ? emit('change',{name:21231,data:456}) } defineExpose({ ? ? change,props }) </script>
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue跳轉(zhuǎn)外部鏈接始終有l(wèi)ocalhost的問題
這篇文章主要介紹了vue跳轉(zhuǎn)外部鏈接始終有l(wèi)ocalhost的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03vue輪播組件實現(xiàn)$children和$parent 附帶好用的gif錄制工具
這篇文章主要介紹了vue輪播組件實現(xiàn),$children和$parent,附帶好用的gif錄制工具,需要的朋友可以參考下2019-09-09Vue.js第二天學(xué)習(xí)筆記(vue-router)
這篇文章主要為大家詳細介紹了Vue.js第二天的學(xué)習(xí)筆記,關(guān)于vue-router的使用方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-12-12Vue中iframe?結(jié)合?window.postMessage?實現(xiàn)跨域通信
window.postMessage()?方法可以安全地實現(xiàn)跨源通信,在一個項目的頁面中嵌入另一個項目的頁面,需要實現(xiàn)父子,子父頁面的通信,對Vue中iframe?結(jié)合?window.postMessage?實現(xiàn)跨域通信相關(guān)知識感興趣的朋友跟隨小編一起看看吧2022-12-12