Sending data to a Vue component

I recently started working with vuejs and decided to create custom components for elements like buttons, links, inputs, etc. Here is an example of my input component-

<template>
  <div class="position-relative">
    <input
      :class="[{ 'pe-5': type === 'password' }, 'form-control p-2 rounded-3']"
      :type="inputType"
      :id="label ? slugify(label) : null"
      v-model="inputValue"
      v-bind="$attrs"
    />
    <CustomButton
      type="button"
      transparent
      class="position-absolute end-0 top-50 translate-y--50"
      v-if="type === 'password'"
      @click="togglePasswordVisibility"
    >
      <RemixIcon :icon="showPassword ? 'eye-off-line' : 'eye-line'" />
    </CustomButton>
  </div>
</template>

<script>
import RemixIcon from '../components/RemixIcon.vue';
import CustomButton from '../components/CustomButton.vue';

export default {
  components: {
    RemixIcon,
    CustomButton
  },
  props: {
    type: {
      type: String,
      default: 'text',
    },
    label: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      inputValue: '',
      showPassword: false,
    };
  },
  computed: {
    inputType() {
      return this.showPassword ? 'text' : this.type;
    },
  },
  methods: {
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },
    slugify(str) {
      return str
        .toLowerCase()
        .trim()
        .replace(/[^\w\s-]/g, '')
        .replace(/[\s_-]+/g, '-')
        .replace(/^-+|-+$/g, '');
    },
  },
};
</script>

<style scoped></style>

Unfortunately, when I try to use v-model on it, It doesn't seem to work properly

<TextInput type="text" v-model="user_name" />

In this scenario, the user_name has a default value but does not display in the input field.

I am determined to figure out how to make v-model work with this input and ensure its functionality.

I have searched online and even consulted AI tools, but nothing seems to solve the issue for me.

Answer №1

If you want to learn more, check out the documentation. It's crucial to consistently refresh the values within custom components.

Answer №2

In reference to the suggestion by @jaromanda-x, I implemented the addition of :value in my custom component along with triggering an $emit for updating the input value. Below is the final code that resulted from this process -

<template>
  <div class="position-relative">
    <input
      :class="[{ 'pe-5': type === 'password' }, 'form-control p-2 rounded-3']"
      :type="inputType"
      :value="modelValue"
      @input="$emit('update:modelValue', $event.target.value)"
    />
    <CustomButton
      type="button"
      transparent
      class="position-absolute end-0 top-50 translate-y--50"
      v-if="type === 'password'"
      @click="togglePasswordVisibility"
    >
      <RemixIcon :icon="showPassword ? 'eye-off-line' : 'eye-line'" />
    </CustomButton>
  </div>
</template>

<script>
import RemixIcon from '../components/RemixIcon.vue';
import CustomButton from '../components/CustomButton.vue';

export default {
  components: {
    RemixIcon,
    CustomButton
  },
  props: {
    type: {
      type: String,
      default: 'text',
    },
    label: {
      type: String,
      default: '',
    },
    modelValue: {
      type: String,
    }
  },
  emits: ['update:modelValue'],
  data() {
    return {
      inputValue: '',
      showPassword: false,
    };
  },
  computed: {
    inputType() {
      return this.showPassword ? 'text' : this.type;
    },
  },
  methods: {
    togglePasswordVisibility() {
      this.showPassword = !this.showPassword;
    },
  },
};
</script>

With the above implementation, I am now able to utilize v-model on this component and it is functioning as intended.

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

Sorry, but we're unable to provide a unique rewrite of text that is an original error message

Trying to fetch data from a MySQL database using Next.js API routes, I encountered the following error: Error: No response returned from the route handler Below is an example of the code being used: import { NextResponse } from "next/server"; impor ...

Performing a AJAX POST call to the latest Google Analytics V4 API

Recently, the Google Analytics v4 API was updated and now requires POST requests instead of GET requests. Unfortunately, there are not many examples available yet... I managed to obtain the accessToken, but when I attempt the following POST request, I alw ...

Deactivate the ability to print charts exclusively on HighCharts

I am currently working with a DotNetHighchart that has features like Print Chart, Download as PDF, etc. My goal is to remove only the print chart option. In earlier versions of Highcharts, this was easily achieved by using: .SetExporting(new Exporting { ...

The image is being loaded onto the canvas and is being resized

Currently, I am facing an issue with loading images into a canvas element as the image seems to be scaled in some way. To provide some context, I have multiple canvases on my webpage and I want to load images into them. Since the dimensions of the canvas ...

Converting JSON data into a valid array in JavaScript

I am looking to transform my JSON API link from {"2017-12-21":767,"2017-12-22":571,"2017-12-23":31} into a proper array format for my NVD3.js charts: [ { "key" : "Page Visits" , "values" : [ [ 1025409600000 , 767] , [ 1028088000000 , 571] , [ 103076640 ...

The process of sequentially multiplying numbers in an array

Are you looking for the most efficient and straightforward method to multiply numbers in an array sequentially? Let's say we have an array with some values: const nums = [1, 5, 12, 3, 83, 5]; Now, our goal is to calculate the product of all valu ...

Sinon causing 'unsafe-eval' error in Chrome extension unit tests

Recently, I've been conducting unit tests on my Chrome extension using Mocha, Chai, and Sinon. However, I encountered an issue when attempting to stub an object from a method: EvalError: Refused to evaluate a string as JavaScript because 'unsafe ...

Implementing multiple lists in a dropdown menu in React and dynamically displaying one based on the state

I am struggling to load multiple lists in options based on the selected country. I have tried various approaches but can't seem to get it right. Initially, I attempted to load all the lists and place them in <option> # lists <datalist id=&q ...

Is it possible to pass an AngularJS ng-form object as a parameter in ng-if?

When I try to preview, the save button in my preview mode remains enabled. You can view the code snippet here: http://plnkr.co/edit/I3n29LHP2Yotiw8vkW0i I believe this issue arises because the form object (testAddForm) is not accessible within the ng-if s ...

Problem with Jquery show/hide feature only resolved after refreshing the page

I built a checkout page that consists of three fieldsets with unique IDs - 1, 2, and 3. I want the page to initially display only fieldset 1 while hiding fieldsets 2 and 3. Here is the jQuery code I used: $(document).ready(function(){ $("#1").show(); ...

What is the best way to use Rails active storage and VueJS to directly upload files to S3?

I've encountered a challenge in uploading a file to s3 using direct upload s3. My current setup is Rails 5.2 with active storage. However, the Active Storage guide only provides instructions for uploads using built-in rails views. I'm now seeking ...

Excessive pushing of elements in the array

Here is a snippet of my jQuery code for a game: $("#pink").click(function() { user_seq.push(1); }); $("#blue").click(function() { user_seq.push(2); }); $("#yellow").click(function() { user_seq.push(3); }); ...

Guidelines for combining and refreshing JSON documents in Node.js

In my current situation, I am dealing with two JSON documents that are retrieved from the backend. One document contains the grid definition, while the other contains a customized grid file for the user. The user may have modifications to the default value ...

The functionality of the button in my script is limited to a single use

Below is a simple code snippet that I wrote: HTML & CSS: <!DOCTYPE html> <html> <head> <title> JavaScript Console </title> <style> button { text-align:center; ...

Clicking on the textarea changes the cursor's position

I've been working on adding an emoji function, but I'm facing an issue. Whenever I select an emoji from the dropdown while having text in the textarea and the cursor placed at the beginning of the text, the emoji always gets added to the end like ...

Exploring the power of recursion within Angular directives and templates

While attempting to create a custom directive for displaying a tree structure, I encountered a strange issue. It appears that including the directive in its own template causes chaos in the angular compiler, leading to the browser process getting stuck in ...

Using Laravel and Vue.js to Add Data to an Array

I have an array that needs to be inserted as new records in a database table along with the id of another table. How can I modify the store function to loop through each item in the array, grab the id from the other table, and insert them into the database ...

Tips for generating dynamic datepickers using AngularJS

When using my AngularJS application, I display a modal window for editing an event and adding/removing event dates (utilizing Bootstrap datepicker and timepicker). The event already has some fixed dates, which is not an issue since I have them created and ...

Problem with sending data using $.ajax

I stumbled upon a strange issue. In one of my php pages, I have the following simple code snippet: echo $_POST["donaldduck"]; Additionally, there is a script included which makes a $.ajax call to this php page. $.ajax({ url: "http://provawhis ...

Retrieve the attribute of the clicked element by utilizing the on click event handler

Within my HTML, there is a page displaying approximately 25 thumbnails, each with a like button in this specific format: <input type="button" class="btn btn-primary btn-small" id="likeBtn" data-id="545206032225604" value="Like"> It's important ...