【问题标题】:Vue 3: make depended props of other props in one componentVue 3:在一个组件中制作其他道具的依赖道具
【发布时间】:2021-03-04 09:53:03
【问题描述】:

我想制作一个组件,其 props 将直接相互依赖。

用法1(当variant="first"我必须设置heightwidth一定不可用):

<Example variant="first" :height="100" />

用法2(当variant="second"我必须设置widthheight一定不可用):

<Example variant="second" :width="100" />

Example组件的代码:

export default defineComponent({
    props: {
        variant: {
            type: String,
            required: true,
            validator: function(value) {
                // The value must match one of these strings
               return ['first', 'second'].indexOf(value) !== -1
            }
        },
        height: {
            type: Number,
            required: true // <-- Only when variant is "first"
        },
        width: {
            type: Number,
            required: true // <-- Only when variant is "second"
        }
    }
}

来自 React 的示例:

const Example = (
    props:
        { variant: "First"; height: number } |
        { variant: "Second"; width: number }
    ) => {
    /*...code...*/
};

如何在 Vue 3 + TypeScript 中做到这一点?

【问题讨论】:

    标签: javascript vue.js vuejs3


    【解决方案1】:

    您可以尝试使用可用于道具的validator 函数。

    docs

    validator: Function 自定义验证器函数,将 prop 值作为唯一参数。在非生产环境中,如果此函数返回错误值(即验证失败),将引发控制台警告。

    或者,您可以通过像mounted 这样的生命周期挂钩或使用watch 添加自定义验证。如果您知道 prop 值没有变化,生命周期方法是OK,如果它们不是静态的,则使用watch,这是一个更可靠的解决方案。

    【讨论】:

    • 所描述的解决方案都不会在编译时提供正确的打字稿验证:(
    猜你喜欢
    • 2021-12-20
    • 2021-09-07
    • 2021-12-12
    • 2020-12-21
    • 2020-09-12
    • 2018-03-17
    • 2018-09-23
    • 2020-10-22
    • 2021-06-27
    相关资源
    最近更新 更多