Value retrieved from input form in vue.js3 v-model is not included in variable

Asked 1 years ago, Updated 1 years ago, 411 views

I'd like to call the API by setting the username obtained by v-model in const data like ↓.
The username in const data is still empty even if I check what I gave you when I threw the request.
How can I set a value for username in const data?
AP We have already checked until API can be called.

<body>
<divid="app">
<input type="text" id="username" v-model="username" autocomplete="off"placeholder="Enter username">
<button:class="btnClass"@click="loginauth">Login</button>
</div>
  <script>


    const {createApp,ref} = Vue;
    CreateApp({
      setup(){
        const username = ref(');

        const data = {
          'username': username.value
        };

        const config = {
          headers:{
            'Content-Type': 'application/json; charset=utf-8',
            'X-CSRF-TOKEN': 'ZZZZZZ'
          }
        };

        constloginauth=()=>{
          axios.post('/test', data, config)
            .then(function(response){
              console.log(response);
            })
            .catch(function(error){
              console.log(error);
            });
        };

        US>return{
          username,
          loginauth
        };
      }
    }).mount('#app');

  </script>
</body>

vuejs

2022-12-06 23:26

1 Answers

username.value has been retrieved in setup, but the raw value has been retrieved at this point.(ref value is not reactive)

Unlike the Reacthooks life cycle, the Composition API setup is performed at the time of component creation, so this does not change the value.

To achieve the expected behavior, for example,

const loginauth=()=>{
          const data = {
            'username': username.value
          }

          axios.post('/test', data, config)
            .then(function(response){
              console.log(response);
            })

You may want to retrieve the value at the required time, such as in .


2022-12-06 23:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.