美文网首页
vueuse的用法

vueuse的用法

作者: wyc0859 | 来源:发表于2022-04-23 18:53 被阅读0次

useVModel

v-model 绑定的简写,props + emit -> ref

先看v-model的写法

defineProps({
  isShow: {
    type: Boolean,
    required: true
  }
})
const emits = defineEmits(['update:isShow'])
function close() {
  emits('update:isShow', false)
}

useVModel的写法

父组件
import { ref } from 'vue'
import addAd from './add_ad.vue'
const isShow = ref(true)

<addAd v-model:isShow="isShow" />
子组件
const props = defineProps({
  isShow: {
    type: Boolean,
    required: true
  }
})
const emit = defineEmits(['update:isShow'])
const eisShow = useVModel(props, 'isShow', emit)
function close() {
  eisShow.value = false
}

<div @click="close">{{eisShow}}</div>
结果显示eisShow是true,点击后变false。此时父组件的isShow由原来的true变成false

当父组件没定义props里的isShow值,子组件可以用withDefaults给默认值

子组件
interface Props {
  isShow: boolean
}
const props = withDefaults(defineProps<Props>(), {
  isShow: true
})

const emit = defineEmits(['update:isShow'])
const eisShow = useVModel(props, 'isShow', emit)
function close() {
  eisShow.value = false
}

<div @click="close">{{eisShow}}</div>
结果显示eisShow是true,点击后变false
此时父组件的isShow由原来的undefined变成false

如果有多个props值,并多处调用,那用useVmodel才有意义

相关文章

网友评论

      本文标题:vueuse的用法

      本文链接:https://www.haomeiwen.com/subject/dmgaertx.html