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

Vue3 <script setup>变量无法在模板渲染问题求助(AWS Amplify场景)

问题原因与解决方案

你代码里的firstname是普通常量,不是Vue3的响应式变量,所以就算修改了它的值,模板也不会自动更新渲染。Vue3的<script setup>里,必须用ref或reactive声明响应式状态,才能让模板和数据同步。

具体修改步骤

  • 从Vue导入ref:
import { onMounted, ref } from 'vue';
  • 把普通变量改成响应式ref变量:
const firstname = ref('');
  • 修改值时,需要通过.value访问(这是ref变量的特性):
firstname.value = response.data.getStudent.firstname;

修改后的完整代码

<script setup>
import { Authenticator } from "@aws-amplify/ui-vue";
import "@aws-amplify/ui-vue/styles.css";
import { generateClient } from 'aws-amplify/api';
import { getStudent } from '../graphql/queries';
import { getCurrentUser } from "aws-amplify/auth";
import { Amplify } from 'aws-amplify';
import config from '../amplifyconfiguration.json';
import { onMounted, ref } from 'vue'; // 新增ref导入

Amplify.configure(config);
const client = generateClient();
const firstname = ref(''); // 改为响应式ref变量

async function currentAuthenticatedUser() {
  try {
    const { username, userId, signInDetails } = await getCurrentUser();
    return username;
  } catch (err) {
    console.log(err);
  }
}

async function loggedInUserData() {
  const loggedInUserId = await currentAuthenticatedUser(); 
  const response = await client.graphql({
    query: getStudent,
    variables: { id: loggedInUserId }
  });
  console.log(response.data.getStudent.firstname);
  firstname.value = response.data.getStudent.firstname; // 通过.value赋值更新
}

onMounted(() => {
  loggedInUserData();
});
</script>

<template>
  <div>
    ...
    ...
    <authenticator>
      <template v-slot="{ user, signOut }">
        <div class="pl-36">Hello {{ firstname }}!</div>
        <button @click="signOut" class="ml-36">Sign Out</button>
      </template>
    </authenticator>
  </div>
</template>

额外说明

Authenticator的插槽已经提供了user对象,如果你只需要Cognito自带的用户信息,可以直接用{{ user.username }}这类字段,但你这里是从DynamoDB查询自定义用户数据,所以用响应式变量的方式是正确的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 05:34:59