当前位置:
首页
文章
前端
详情

Vue3 defineProps定义属性使用总结

一、无默认值

Children.vue

<template>
  <p v-if="props.visible">Hello World</p>
</template>

<script setup>
const props = defineProps<{
  visible: boolean
}>()
</script>

Parent.vue

<template>
  <Children :visible="true" />
</template>

<script setup>
import Children from './Children'
</script>

二、有默认值

Children.vue

<template>
  <p >{{ props.msg }}</p>
</template>

<script setup>
const props = withDefaults(defineProps<{
  msg?: string
}>(), {
  msg: 'Hello World'
})
</script>

Parent.vue

<template>
  <Children />
</template>

<script setup>
import Children from './Children'
</script>

三、监听属性变化

Children.vue

<template>
  <p v-if="props.visible">Hello World</p>
</template>

<script setup>
import { watch } from 'vue'

const props = defineProps<{
  visible: boolean
}>()

// 监听单个属性值变化
watch(() => props.visible, (newV: boolean) => {
  if(newV) {
    // ...
  }
})
</script>

Parent.vue

<template>
  <Children :visible="true" />
</template>

<script setup>
import Children from './Children'
</script>

免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。