唯品秀前端博客

组件数据传递一直是学习MVVM前端框架的重中之重,那么在vue3-setup下,props,emit怎么获取呢?setup script语法糖提供了新的API来供我们使用

defineProps父传子

父组件代码

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>

子传父defineEmits

子组件

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>

defineExpose

组件暴露出自己的属性,在父组件中可以拿到,可以理解为“子传父”方式,示例:

子组件

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值
})

v-model传值

父组件

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
}
本站所有文章、图片、资源等如无特殊说明或标注,均为来自互联网或者站长原创,版权归原作者所有;仅作为个人学习、研究以及欣赏!如若本站内容侵犯了原著者的合法权益,可联系我们进行处理,邮箱:343049466@qq.com
赞(0) 打赏
标签:

上一篇:

下一篇:

相关推荐

0 条评论关于"Vue3中父子组件通信以及v-model双向数据传值"

表情

最新评论

    暂无留言哦~~
谢谢你请我吃鸡腿*^_^*

支付宝扫一扫打赏

微信扫一扫打赏