Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Extracting props to separate module in Vue composition API in typescript

I am trying to port some old code from Vue options API + JS to Vue composition API + TS and I have the following mixin:

export default {
  props: {
    time: {
      default: 1,
      type: String | Number,
    },
    iterations: {
      default: 1,
      type: String | Number,
    },
  },
  data: () => ({
    animation: '',
  }),
  methods: {
    animate() {
      this.animation = `move ${this.time}s ease-in-out ${this.iterations} forwards`
    },
  },
}

Now I am having some trouble to find the right way to type the props while at the same time preserving the default values and the reactivity. In this one for example the default values get lost:

export default (props: {
  time: string | number
  iterations: string | number
}) => {
  const animation = ref('')
  const animate = () => {
    animation.value = `move ${props.time}s ease-in-out ${props.iterations} forwards`
  }
  return {
    animation,
    animate,
  }
}

Whereas here I lose the reactivity since I destructure the props param:

export default ({
  time = 1,
  iterations = 1,
}: {
  time: string | number
  iterations: string | number
}) => {
  const animation = ref('')
  const animate = () => {
    animation.value = `move ${time}s ease-in-out ${iterations} forwards`
  }
  return {
    animation,
    animate,
  }
}

How can I fix that?

question from:https://stackoverflow.com/questions/66067984/extracting-props-to-separate-module-in-vue-composition-api-in-typescript

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

1 Reply

0 votes
by (71.8m points)

I will go for the second solution and add an export for the props object

export const moduleProps {
  time: {
    default: 1,
    type: [String, Number],
  },
  iterations: {
    default: 1,
    type: [String, Number],
  },
}

A bit redundant but it works


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...