Search code examples
vue.jsvue-componentelement-ui

why setup() doesnt work "Cannot read property 'username' of undefined "


when i use toLogin in methods it works, but use in setup and return(in this code - test) i get error Cannot read property 'username' of undefined doesnt work, why?

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");
    },
  },
};

Solution

  • You don't need this. Instead, just use console.log(username.value). username is already captured in scope for the test function to use.

    The docs here https://v3.vuejs.org/guide/composition-api-introduction.html#setup-component-option contain this example:

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