简体   繁体   中英

Reactivity for Vue props that are objects

I have a component that has a prop called value (used for v-model ) and the type of the prop is an object. Here is an example value of the prop value :

{type: "column": {value: {column: "col1", anotherattr: "test"}}}

However; if I pass the following value to the component, it causes reactivity problems since anotherattr is not defined here:

{type: "column": {value: {column: "col1"}}}

I want the component to be able to validate the schema and make the attributes reactive automatically because anotherattr is actually an optional property.

What's the suggested approach here? I thought about using validator but it looked like an anti-pattern since it's used for validation. Is there any practical approach to this problem? (Maybe Typescript be helpful?)

With Typescript you could do something like this:

export class YourProp {
    constructor(
        public value: YourValue
    )
}

export class YourValue {
    constructor (
        public columnName: String,
        public anotherAttr: String = "default" // give it a default value since its optional
)

And then don't handle the prop as an Object but as an instance of YourProp.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM