4***@qq.com
4***@qq.com
  • 发布:2025-03-24 21:10
  • 更新:2025-03-25 17:14
  • 阅读:52

uni-app-x,uts不支持vue3中的组合式函数吗

分类:uni-app x

list.uvue:

<script setup lang="uts">  
    import { useCounter } from './useCounter.uts'  
    const { count, increment } = useCounter(123)  
        ...  
</script>

useCounter.uts

import { ref } from 'vue'  

export function useCounter(initialValue: number = 0) {  
    // 计数器值  
    const count = ref<number>(initialValue)  

    // 增加计数  
    const increment = (): void => {  
        count.value++  
        console.log("+++ 当前计数:", count.value)  
    }  
    // 返回需要暴露的变量和方法  
    return { count, increment }  
}

list.uvue报错:

20:52:50.331 [plugin:uni:app-uts] 编译失败
20:52:50.331 ‌error: Function invocation 'count()' expected‌
20:52:50.331 at pages/test/list.uvue:60:9
20:52:50.331 58 | // const d = useCounter(123)
20:52:50.331 59 | // console.log('f1++', d.value);
20:52:50.332 60 | const { count, increment } = useCounter(123)
20:52:50.332 | ^
20:52:50.332 61 |
20:52:50.333 62 |
20:52:50.333 ‌error: Unresolved reference: increment‌
20:52:50.333 at pages/test/list.uvue:60:16
20:52:50.333 58 | // const d = useCounter(123)
20:52:50.333 59 | // console.log('f1++', d.value);
20:52:50.333 60 | const { count, increment } = useCounter(123)
20:52:50.333 | ^
20:52:50.333 61 |
20:52:50.333 62 |

2025-03-24 21:10 负责人:无 分享
已邀请:
rice_z

rice_z

需要给 useCounter 定义 返回值的类型

export function useCounter(initialValue: number = 0) {    
    // 计数器值    
    const count = ref<number>(initialValue)    

    // 增加计数    
    const increment = (): void => {    
        count.value++    
        console.log("+++ 当前计数:", count.value)    
    }    
    // 返回需要暴露的变量和方法    
    return { count, increment }  as 函数返回值的类型  
}
  • 4***@qq.com (作者)

    可以了!!我加了一个type类型来描述返回值就可以了。感谢!!!


    export type Counter = {

    count: Ref<number>

    increment: () => void

    }

    export const useCounter = (initialValue: number): Counter => {

    // 计数器值

    const count = ref<number>(initialValue)

    // const d = initialValue;


    // 增加计数  
    const increment = (): void => {
    count.value++
    console.log("+++ 当前计数:", count.value)
    }

    // 返回需要暴露的变量和方法
    return { count, increment }

    }

    2025-03-25 17:13

4***@qq.com

4***@qq.com (作者)

这样就可以work了。

export type Counter = {  
    count: Ref<number>  
    increment: () => void  
}  
export const useCounter = (initialValue: number): Counter => {  
    // 计数器值  
    const count = ref<number>(initialValue)  
    // const d = initialValue;  

    // 增加计数  
    const increment = (): void => {  
        count.value++  
        console.log("+++ 当前计数:", count.value)  
    }  

    // 返回需要暴露的变量和方法  
    return { count, increment }  
}

要回复问题请先登录注册