组件数据传递一直是学习MVVM前端框架的重中之重,那么在vue3-setup下,props,emit怎么获取呢?setup script语法糖提供了新的API来供我们使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | <template> <div class="die"> <h3>我是父组件</h3> <zi-hello :name="name"></zi-hello> </div> </template> <script setup> import ziHello from './ziHello' import {ref} from 'vue' let name = ref('默认值111') </script> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <template> <div> 我是子组件{{name}} // 默认值111' </div> </template> <script setup> import {defineProps} from 'vue' defineProps({ name:{ type:String, default:'我是默认值' } }) </script> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <div> 我是子组件{{name}} <button @click="ziupdata">按钮</button> </div> </template> <script setup> import {defineEmits} from 'vue' //自定义函数,父组件可以触发 const em=defineEmits(['myUpdata']) const ziupdata=()=>{ em("myUpdata",'我是子组件的值') } </script> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <template> <div class="die"> <h3>我是父组件</h3> <zi-hello @myUpdata="updata"></zi-hello> </div> </template> <script setup> import ziHello from './ziHello' const updata = (data) => { console.log(data); //我是子组件的值 } </script> |
组件暴露出自己的属性,在父组件中可以拿到,可以理解为“子传父”方式,示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <template> <div> 我是子组件 </div> </template> <script setup> import {defineExpose,reactive,ref} from 'vue' let ziage=ref(18) let ziname=reactive({ name:'小李' }) //暴露出去的变量 defineExpose({ ziage, ziname }) </script> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <template> <div class="die"> <h3 @click="isclick">我是父组件</h3> <zi-hello ref="zihello"></zi-hello> </div> </template> <script setup> import ziHello from './ziHello' import {ref} from 'vue' const zihello = ref(); // 父组件通过ref读取子组件上暴露出来的值 const isclick = () => { console.log('接收ref暴漏出来的值',zihello.value.ziage) console.log('接收reactive暴漏出来的值',zihello.value.ziname.name) } </script> |
注意,如果父组件初始化想渲染子组件暴露传过来的值,一定要在onMounted里去赋值(关于defineExpose数据响应式参考),例如:
1 2 3 4 5 6 7 | // 父组件取值 let zihello = ref(); let childrendata = ref(''); // console.log(zihello.value.val); // 注意,在这里是无法直接获取到子组件zihello的value值 onMounted(() => { childrendata.value = unref(zihello).val // 获取子组件暴露的val值 }) |
1 2 3 4 5 | <List v-model:num='num'></List> <script setup> import List from '../components/List.vue' let num = ref(1); </script> |
1 2 3 4 5 6 7 8 9 10 | const props = defineProps({ num: { type: Number, default: 100 } }) const emit = defineEmits(['update:num']); // 固定语法,'update:num'的num为props接收值的名称 const btn = () => { emit('update:num', 200); //将值由1改为200 } |
上一篇:Vue3中watch使用方式及watchEffect光速了解
下一篇:Vue 3任意传送门Teleport-王者荣耀大桥传送大招上线至Vue3了
支付宝扫一扫打赏
微信扫一扫打赏
共 0 条评论关于"Vue3中父子组件通信以及v-model双向数据传值"
最新评论