为什么 setup() 不起作用“无法读取未定义的属性‘用户名’”

问题描述

当我在方法中使用 toLogin 时它可以工作,但在设置和返回中使用(在此代码中 - 测试)我收到错误无法读取未定义的属性用户名”不起作用强>,为什么?

export default {
  name: "Login",setup() {
    const username = ref("");
    const password = ref("");
    const router = useRouter();


    
    const test = async () => {
      console.log(this.username.value)
    }
    return {
      username,password,router,test
    };
  },methods: {
    async toLogin() {
      const rep = await axios.post("login",{
        username: this.username,password: this.password,});
      console.log(rep)
      //await this.router.push("/successlogin");
    },},};

解决方法

您不需要this。相反,只需使用 console.log(username.value)username 已被捕获在 test 函数的范围内以供使用。

此处的文档 https://v3.vuejs.org/guide/composition-api-introduction.html#setup-component-option 包含此示例:

setup (props) {
  const repositories = ref([])
  const getUserRepositories = async () => {
    repositories.value = await fetchUserRepositories(props.user)
  }

  return {
    repositories,getUserRepositories
  }
}