简体   繁体   中英

how to get the input value in setup code block using vue3

I want to use vue3 to write a login page. I define a input in the vue3 component template like this follow the docs:

<template>
  <div id="app">
    <div id="wrap">
      <ul class="nav nav-tabs">
        <li>
          <input :value="username" placeholder="username" @input="$emit('update:username',$event.target.value)"/>
          <input v-model="password" placeholder="password" />
          <button @click="login">Login</button>
        </li>
      </ul>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  props: ['username'],
  setup() {
    const login = (() => {
      alert(this.username);
    })

    return {
      login,
      username:""
    };
  },
  components: {
  },
  computed: {
    value: {
      get() {
        return this.username;
      },
      set(v: any) {
        this.$emit('update:username', v);
      },
    },
  },
});
</script>

now I want to get the username from the input, what should I do? I tried to use this.username but it could not find the variable username.

try to tweak your template input like this:

<input 
 :value="props" 
 placeholder="username" 
 v-on:input="updateValue($event.target.value)"/>

and get the username in setup code block like this:

setup() {
    function updateValue(value: any) {
      console.log("current username:" + value);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM