Component reusability in Vue.js: Take control of your input

I've been utilizing a UI component from

My intention is to develop a reusable component for vue-tags-input, and here is the code I am currently working on:

components/UI/BaseInputTag.vue

<template>
  <b-form-group :label="label">
    <no-ssr>
      <vue-tags-input
        :value="tags"
        @tags-changed="updateValue"/>
    </no-ssr>
  </b-form-group>
</template>

<script>
  export default {
    name: 'BaseInputTag',
    props:   {
      label: { type: String, required: true },
      value: { type: [String, Number, Array] },
      tags: { type: [Array] }
    }, 
    methods: {
      updateValue(newTags) {
        this.$emit('input', newTags);
      }
    }
  }
</script>

Furthermore, in my parent vue page. I'm incorporating the above component with the following code:

pages/users/new.vue

<BaseInputTag v-model="tag" :tags="interests" label="Interests"/>

<script>
  export default {
    name: 'InsiderForm',
    data() {
      return {
        tag: '', 
        interests: []
      };
    }
  }
</script>

How would it be possible for me to emit the child component's newTags back to the parent's data as interests

Answer №1

You're almost there!

Let's keep pushing forward:

<CustomInputField v-model="data" :items="listData" @change="updateParentState" label="List of Items"/>

<script>
  export default {
    name: 'ParentComponent',
    data() {
      return {
        data: '', 
        listData: []
      };
    },
    methods: {
      updateParentState (newValue) {
        console.log('Received new value from child', newValue)
      }
    }
  }
</script>

Answer №2

I successfully implemented the solution, sharing my code below:

child-component

<template>
  <b-form-group :label="label">
    <no-ssr>
      <vue-tags-input
        :value="value"
        v-model="tag"
        placeholder="Add Tag"
        :tags="tags"
        @tags-changed="updateValue"/>
    </no-ssr>
  </b-form-group>
</template>

<script>
  export default {
    name: 'BaseInputTag',
    props:   {
      label: { type: String, required: true },
      value: { type: [String, Number, Array] },
      tags: { type: [Array, String] },
      validations: { type: Object, required: true }
    }, 
    data() {
      return {
        tag: ''
      }
    },
    methods: {
      updateValue(newTags) {
        this.$emit('updateTags', newTags);
      }
    }
  }
</script>

To handle changes in the parent component:

<BaseInputTag :tags="interests" @updateTags="interests = $event" label="Interests"/>


<script>
  export default {
    name: 'InsiderForm',
    data() {
      return {
        tag: '', 
        interests: []
      };
    }
  }
</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

"Preventing Cross-Origin Requests" error encountered while trying to load a JSON document

I've been working on an online experiment using JavaScript, and I need to load parameters for the task from a JSON file. I managed to do this successfully when running the task through a live server. However, if I try to run it locally by opening the ...

Firing a custom jQuery event when a page loaded via AJAX is complete, ensuring it is triggered

I am facing an issue with a particular scenario. There is a page that contains a script to load a child page and log a custom event, which is triggered in a Subform. --Index.html-- <body> <input type="button" class="clickable" value="Load child ...

Utilize CSS with dynamically created elements

I am currently figuring out how to use my .each() function with a $(document).ready and a click event. Here's what I have so far: $(document).ready(function(){ $(".help-inline").each(function() { $(this).css('display', 'none&apos ...

The environment variable process.env.variable works perfectly fine during local development, however, it seems to malfunction once the application is deployed to Heroku within

Currently, I am utilizing nuxt.js and attempting to display images dynamically. To achieve this, I have implemented the BASE_URL variable within the .env file, allowing me to access image files based on the set BASE_URL in my local environment. .env file ...

The MUI Theming feature with primary color set to light seems to be causing confusion with the light color property

Trying to grasp the concept of MUI theming. There is a section dedicated to theming where it mentions the ability to change the theme. My query is: Within the primary color, there are three colors that can be defined: main, dark, and light. I'm unsur ...

In Angular-Cli, the variables @Input and @Output are consistently null until they are assigned

Individuals' internal values are printed without any problems, but those obtained using @Input or @Output are not being displayed. child.component.ts @Component({ selector: 'app-form-input', templateUrl: './form-input.component.ht ...

Error: The value of "$tweetId" cannot be parsed as it is set to "undefined". Please ensure that string values are properly enclosed

I am utilizing sanity, and if you require more details, I will furnish it promptly. When I try to access http://localhost:3000/api/getComments, I encounter the following error message: ClientError: Unable to process value of "$tweetId=undefined". Kindly ...

The function did not execute properly, resulting in the express route returning no value

Encountering some issues with Express routes that are behaving inconsistently despite having identical code execution. The goal is to have a client application make API calls like this: async search(){ const query = this.$refs.searchInput.value; ...

Determine the position of a nested object within a multidimensional array using JavaScript/TypeScript

My objective is to obtain the complete index of a complex object within a multidimensional array. For example, consider the following array: var arr = [ { name: "zero", children: null }, { name: "one", children: [ { ...

Guide to Producing an Unorthodox 3D Polygon Extruded Form using React-Three-Fiber

Up until now, I've only utilized useBox statement to create 3D rectangles. Is there a method available to generate something like a wooden piece in dimensions of "two by four" with cut ends at specific angles, akin to the image shown below? https://i ...

Check to see if two sets of coordinates fall within the specified radius

I'm currently working on analyzing the collision data for major intersections in my city by aggregating it with the location information. My main goal is to determine the number of accidents that occurred within a 20-meter radius of each intersection. ...

Sort through the angular data using an array of identifiers

I am working with a json file that contains my data [{"id":"349","title":"event 1"},{"id":"350","title":"event 2"},{"id":"351","title":"event 3"}] Users have the ability to save events to local storage, which are then stored in an array $storage.myEven ...

Expanding the input focus to include the icon, allowing it to be clicked

Having trouble with my date picker component (v-date-picker) where I can't seem to get the icon, a Font Awesome Icon separate from the date-picker, to open the calendar on focus when clicked. I've attempted some solutions mentioned in this resour ...

Choose an option removed upon clicking

I need to remove the option with a value of 0 when the user selects from the dropdown list. Choose: <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <form:select id="CONTEXTE" path="CONTEXTE" onclick="go()" class="s ...

Guide on Implementing Link href in Next.js v12

When I set the href as a string, the link functions properly. However, when I use an object for the href, the link fails to work. Despite seeing the correct querystring when hovering over the link, it always takes me back to the first page. // ProdCard t ...

Is it possible to conceal the contents of a details tag without using a summary tag?

I'm looking for a way to hide the details tag without the summary. In my code, the summary is only visible when a condition [isvisible == false] is met. However, even when the summary is not visible, the details keyword is still shown and I want to hi ...

Unable to upload file to firebase storage - encountering technical issues

After following the documentation on firebase storage, I still can't seem to get my file upload to work properly. Using react, my goal is to successfully upload a file to firebase storage. However, I keep encountering an error message: TypeError: th ...

Leveraging Angular Dragula without the need for RequireJS

I'm eager to incorporate Drag and Drop functionality into my Angular project with the help of the angular-dragula module (https://github.com/bevacqua/angular-dragula). However, it appears that this module heavily relies on RequireJS. My experience wit ...

Vue JS - What is the optimal method for initiating input validation: utilizing the change/key up event on an input or employing watchers on its property?

Which method is most effective for implementing input validation in Vue JS? Should you rely on events like onchange and keyup, or should you use watchers on each property? Keep in mind that there are approximately 20 inputs to manage. ...

Current target in Internet Explorer 10 with Javascript

Encountering a problem with event.currentTarget in IE 10. Two divs are present on the website. The first div contains an image that takes up the entire screen, while the second div is smaller and positioned over the first div. The smaller div has no conte ...