时间:2022-06-22 09:37:39 | 栏目:vue | 点击:次
父亲传值给儿子,儿子可以修改父亲的数据(同步)
<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']) // 触发事件 const change =()=>{ emit('change',{name:21231,data:456}) } defineExpose({ change,props }) </script>