在打字稿中提取道具以分离 Vue 组合中的模块 API
Extracting props to separate module in Vue composition API in typescript
我正在尝试将一些旧代码从 Vue 选项 API + JS 移植到 Vue 组合 API + TS 并且我有以下混合:
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`
},
},
}
现在我很难找到正确的方式来键入道具,同时保留默认值和反应性。例如,在这一个中,默认值丢失了:
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,
}
}
而在这里我失去了反应性,因为我解构了 props 参数:
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,
}
}
我该如何解决?
我将采用第二种解决方案并为 props 对象添加导出
export const moduleProps {
time: {
default: 1,
type: [String, Number],
},
iterations: {
default: 1,
type: [String, Number],
},
}
有点多余但很管用
我正在尝试将一些旧代码从 Vue 选项 API + JS 移植到 Vue 组合 API + TS 并且我有以下混合:
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`
},
},
}
现在我很难找到正确的方式来键入道具,同时保留默认值和反应性。例如,在这一个中,默认值丢失了:
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,
}
}
而在这里我失去了反应性,因为我解构了 props 参数:
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,
}
}
我该如何解决?
我将采用第二种解决方案并为 props 对象添加导出
export const moduleProps {
time: {
default: 1,
type: [String, Number],
},
iterations: {
default: 1,
type: [String, Number],
},
}
有点多余但很管用