VueJs triggering 'input' emission with 2 values

I created a Vue component with an input field and used v-model to bind data. Here is the code:

<template>
  <div class="input-field">
    <input
      type="text"
      v-model="value"
      :id="inputId"
      placeholder=""
      @input="updateText"
    />
    <label :for="inputId">{{ label }}</label>
  </div>
</template>

<script>
import { ref } from "@vue/reactivity";
export default {
  name: "InputField",
  props: {
    value: { type: String },
    inputId: { type: String },
    label: { type: String },
  },
  setup(props, { emit }) {
    const value = ref("");
    const updateText = () => {
      emit("input", value.value);
    };
    return {
      value,
      updateText,
    };
  },
};
</script>

<style lang="less" scoped>
</style>

After using v-model in the parent component, I noticed that the value was not changing. When I console.log, I found two values being returned - one for the input value and another for the ref object.

<div class="login-box">
    <InputField
        v-model="username"
        label="Username "
        inputId="username"
        @input="printUser"
    />
    <input type="text" />
<div>{{ username }}</div>

If anyone has any insights or solutions, I would appreciate your help. Thank you!

Answer №1

The new feature in vue 3 known as v-model for a component is essentially shorthand for

<input-field
  :model-value="username"
  @update:model-value="username = $event"
></input-field>

This implies that your input field component should look like this:

<template>
  <div class="input-field">
    <input
      type="text"
      :value="modelValue"
      :id="inputId"
      placeholder=""
      @input="updateText"
    />
    <label :for="inputId">{{ label }}</label>
  </div>
</template>

<script>
import { ref } from "@vue/reactivity";
export default {
  name: "InputField",
  props: {
    ...
    modelValue: { type: String },
    ...
  },
  setup(props, { emit }) {
    const updateText = (e) => {
      emit("update:modelValue", e.target.value);
    };
    return {
      updateText,
    };
  },
};
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Power of Ajax Interceptor in Framework7-vue-cli

I have a challenge where I need to redirect all ajax requests with a status code of -1 in the response to the login screen. Despite my efforts, I am unable to monitor it. What steps should I take next? Appreciate your help. My approach: app.js Framework7. ...

I encountered a problem with routing in my MERN project while trying to implement a feature I learned from a YouTube tutorial

My first question on stackoverflow. To summarize: I followed a YouTube video and downloaded the course code from the GitHub link provided, but I'm encountering routing issues despite reading similar questions on stackoverflow. I've been followi ...

Transforming mmddyyyy date format to mm/dd/yyyy using Node.js

Need help converting date format Date: "11032020" (mmddyyyy) Desired output: 11/03/2020 Looking to convert this to mm/dd/yyyy in Node.js as a beginner. I've searched for solutions online but couldn't find one that works for my specific case. ...

What is the process for obtaining intersection set data from an array?

I'm trying to find the intersection set within an array only containing type 1 and 2. Can you help me with that? var arr = [ { id: 1, auths: [ { authId: 1, type: 1, value: 'Test1' }, { authId: 2, type: 1, ...

Is there a way to automatically insert a timestamp into a table row and increment the tote number when it changes?

After the user enters their initials, I need to automatically add a timestamp followed by a new line. The tote number of the next line should also increment to the next number (e.g., on line 2, the tote number will be 2). This is the structure of my table ...

Implementing pagination using getServerSideProps in NextJS allows for dynamic

I'm currently using NextJS along with Supabase for my database needs. I'm facing a challenge with implementing pagination as the solution I'm seeking involves passing queries to the API. However, since I'm fetching data directly from th ...

Unable to save session cookie in browser when accessing server from different domain

I am encountering an issue with the browser not saving the session cookie sent from my server. The client web app is hosted on Vercel, while the server app is hosted on Heroku. I utilize passport for signing in, and upon successful authentication, a sessio ...

Implementing a JavaScript function to a button within an existing form in JSP - Best practices

Currently, I am working on developing multiple JSP pages and I encountered a requirement where I needed to add a function to a button within an already existing form. The challenge was that the form's submit button was configured to navigate to anothe ...

Tips for incorporating padding into your Vuetify navbar

I attempted to apply padding to the Vuetify navbar using the px-number attribute, but unfortunately, it did not take effect. I included this code snippet, but the padding did not appear as expected: <v-app-bar color="deep-purple accent-4" dar ...

Swapping out the entire vue.js container

I have a custom vue.js widget that I initialize like so: var myWidget = new Vue({ el: '#widget-container', methods: { loadData:function() { // custom functionality here } }, }); The HTML structure is as f ...

How can you reach a constant from a different component in React?

I am new to developing a react application and struggling with accessing const data from another component. The specific constant I need access to is located in the TableComponent.js file. TableComponent.js export default function({ infinite }) { const [ ...

Transform the object's structure into an array

I've been attempting to modify the format of this object for quite some time: "Obj":{"0":"value1","1":"value2"} My desired output should be like a basic array: "Obj": ["value1","value2"] Is there an easy method to achieve this transformation? App ...

Maintaining a particular section of a sentence in Node.JS

One part of a sentence needs to be kept in order to put it in the argument of a function like this : var sen1 = "Hello this is my email" var final = "this is my email" Being new to Node.js and JS in general, I have heard about the RegExp function but I a ...

Revamp the website's design

I am looking to revamp the color theme of my website with just a click of a button. Can someone provide me with a link to a reference website where I can get some inspiration? ...

Checking if the iframe location has been modified using Jquery

Looking to determine if the location of an iframe has been modified. function checkLocation() { setInterval(function(){alert("Hello")},3000); if (document.getElementById("myiframe").src = 'http://www.constant-creative.com/login';) { } ...

Struggling to make the AJAX script function properly

I have a table containing a list of transactions and I am attempting to update the table contents at specific intervals. The web page is hosted on a Linux Red Hat server, and currently, only the AJAX functionality is not functioning as expected. <!do ...

Navigate to a different URL following a post request using AJAX and EXPRESS

Currently, I am diving into the world of node.js servers by creating a login website. Users can input their username, which is then sent via an ajax post request to the server and stored in an array of all users. My goal is to redirect users to a personali ...

Accessing a hyperlink in an alternative browser

Is there a way to transfer a link from one browser to another? For example, moving a link from Firefox to Chrome or from a Chrome Incognito window to a regular Chrome window. Let me provide more context. I have a webpage that refreshes every second and us ...

Would you suggest this approach for creating a personalized form component in vue 3?

CustomInput.vue <template> <input v-model="customModelValue"> </template> <script setup lang="ts"> import {computed} from "vue"; const customEmit = defineEmits(['update:customModelValue']) ...

The second JSP page fails to load following an AJAX POST request

The following code snippet is found in page1.jsp. $.ajax({ type: "post", url: "page2.jsp", data: newdata, success:function(msg){ return msg; } ...