GeeWhizBang
GeeWhizBang

Reputation: 857

how to define type of :style object vue3 typescript

In the template I have:

 <template>
      <div ref="PopupContent" class="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?

Upvotes: 2

Views: 2634

Answers (3)

GeeWhizBang
GeeWhizBang

Reputation: 857

This is an app example (it doesn't really do anything) but shows you how to set values on the fly for a style in typescript. If you don't set the type, vue3 stops on the getStyle(n).

 <template>
   <template v-for="n in data.count" :key="n">
     <div class="relative" :style="getStyle(n)"></div>
   </template>
 </template>
 <script>
 import { defineComponent, StyleValue } from 'vue';

 export default defineComponent({
   name: "MyApp",
   data() {
     return {
       count: 10,
       isVert: true,
       x: 10,
     };
  },
  methods: {
    getStyle(n: number): StyleValue {
      return this.data.isVert
        ? ({
          height: this.data.x / this.scale + 'px',
          top: this.data.x * n / this.scale + 'px'
        } as StyleValue)
        : ({
          width: this.data.x / this.scale + 'px',
          left: this.data.x * n / this.scale + 'px'
        } as StyleValue)
    },
  },
});
</script>

Upvotes: 0

aseidma
aseidma

Reputation: 752

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: {},
})

Upvotes: 2

Orbis
Orbis

Reputation: 475

I guess you are looking for:

Partial<CSSStyleDeclaration>

Docs:

Partial

CSSStyleDeclaration

Upvotes: 7

Related Questions