You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3 Composition API中computed返回undefined问题求助

Vue3 Composition API自定义Hook中Computed返回Undefined的问题解决

核心问题:变量名拼写不匹配

你在Hook中返回的计算属性是isMatchi,但在模板里引用的是vm.isMatch,少了末尾的i,导致找不到对应属性,所以返回undefined。这是最直接的错误。

其他需要确认的点

  1. 必须导入Vue响应式API
    确保在hook.ts文件顶部正确导入reactive和computed,否则无法创建有效的响应式对象和计算属性:

    import { reactive, computed } from 'vue'
    
  2. 业务逻辑修正(可选)
    原代码中isMatchi只是判断密码长度大于0,如果你实际需求是判断两次输入的密码是否匹配,需要调整计算属性的逻辑:

    const isMatch = computed(() => state.password.length > 0 && state.password === state.repeatPass)
    

修正后的完整代码

hook.ts

import { reactive, computed } from 'vue'

export const useCreatePassVm = () => {
    const state = reactive({
        password: '',
        repeatPass: ''
    })

    // 修正命名+匹配逻辑
    const isMatch = computed(() => state.password.length > 0 && state.password === state.repeatPass)

    // 返回state以便组件能修改密码值,同时返回正确命名的计算属性
    return { state, isMatch }
}

Vue单文件组件

<template>
  <UiText v-if="!vm.isMatch">not match</UiText>
  <!-- 添加输入框用于测试 -->
  <input v-model="vm.state.password" type="password" placeholder="输入密码" />
  <input v-model="vm.state.repeatPass" type="password" placeholder="重复密码" />
</template>

<script setup lang="ts">
import { useCreatePassVm } from './hooks'

const vm = useCreatePassVm()
</script>

额外说明

如果在组件内直接定义能正常工作,是因为组件内的变量名和模板引用完全一致,且处于Vue的响应式上下文当中。而自定义Hook只要在<script setup>或setup()函数内调用,就会自动继承响应式上下文,无需额外处理。

内容的提问来源于stack exchange,提问作者Vii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 09:22:13