Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

vue3 子组件接收的 props 绑定到 v-model 上提示错误

业务场景:子组件引用了 vant 组件 ActionSheet,想要在父组件中点击按钮打开子组件里面的 ActionSheet,父组件通过 visible 属性控制状态。

父组件

<template>
    <button @click="visible = true">打开子组件</button>
    <child v-model:visible="visible" />
</template>

<script>
import { ref, defineComponent } from 'vue'
export default defineComponent({
    setup () {
        const visible = ref(false)

        return {
            visible
        }
    }
})
</script>

子组件

<template>
    <van-action-sheet v-model:show="visible" @close="onClose" />
    <p>...<p/>
</template>

<script>
import { ref, defineComponent } from 'vue'
export default defineComponent({
    props: {
        visible: {
            type: Boolean
        }
    },
    
    emits: ['update:visible']
    
    setup (props, ctx) {
        const onClose = () => {
            ctx.emit('update:visible', false)
        }
    }
})
</script>

但是这样写会报错,提示不能将 props 绑定到 v-model 上,可我又不想在子组件里在定义一个 show 变量控制 ActionSheet 状态,还有其他好的办法吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<van-action-sheet :show="visible" @close="onClose" />

这样即可,因为 props 接收的参数不允许子组件修改,应该通过 $emit 来通知父组件修改。

所以看上去 zhangzp 像是对的,但是具体 van-cation-sheet 会触发到那个事件上还得查一下文档。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...