Home > front end >  how to define type of :style object vue3 typescript
how to define type of :style object vue3 typescript

Time:02-01

In the template I have:

 <template>
      <div ref="PopupContent"  :style="data.contentStyle">
 </template>

In setup I have:

export default defineComponent({
    name: "Popup",
    setup() {
       const data = ref({
       someOtherProp: 0,
       style: <StyleValue>(),
       someOtherOtherProp: false,
       retries: 0,
    });

I can also define some objects as interfaces if I need to, but perhaps there is an existing type that can be used. I still don't know the correct syntax for the setup to do this.

interface StyleProps {
   left: string;
   right: string;
   top: string;
   bottom: string;
   width: string;
   height?: string;
}

If I do this, is there a great way to make these accessible to all of the code that uses them?

I'm trying to find a way to define style that doesn't have problems later in the code trying to set this.data.style["width"], for example.

So in response to one of the answers, this seems to work, but I have a further question:

const style: Partial<CSSStyleDeclaration> = {};
const arrowStyle: Partial<CSSStyleDeclaration> = {};

const data = ref({
   strokeWidth: 0.108,
   style: style,
   arrowStyle: arrowStyle,
});

Is there a way to do this inline on defining const data rather than the awkward defining separate variables?

CodePudding user response:

You can do it elegantly using an interface and generics like this:

interface MyData {
  strokeWidth: number;
  style: Partial<CSSStyleDeclaration>;
  arrowStyle: Partial<CSSStyleDeclaration>;
}

const data = ref<MyData>({
  strokeWidth: 0.108,
  style: {},
  arrowStyle: {},
})

CodePudding user response:

I guess you are looking for:

Partial<CSSStyleDeclaration>

Docs:

Partial

CSSStyleDeclaration

  •  Tags:  
  • Related