"Encountering issues with the @click function not working as expected in Vue

For the past few days, I've been diving into Vue.JS and attempting to create an app that adds a chip when a button is clicked. The chips should display the value from an input field as their name. I've created a method that is supposed to create these chips, but for some reason it's not being called. I've even tried using console.log at the beginning of the method to troubleshoot...

Appreciate any help!

Here's my App.vue:

<template>
  <v-app id="whole_container">
    <v-content id="main_container">
      <v-row id="main_row">
        <v-col class="hellocol" id="chips">
          <customChip name="Louis"></customChip>
        </v-col>
        <v-col class="hellocol" id="chipField">
          <addChip></addChip>
        </v-col>
      </v-row>
    </v-content>
  </v-app>
</template>

<script>
import customChip from './components/chip.vue';
import addChip from './components/addChip.vue';

export default {
  name: 'App',

  components: {
    customChip,
    addChip
  },

  data: () => ({
    //
  }),
};
</script>

My AddChip file:

<template>
    <div>  
        <v-text-field id="newChip" :outlined="true" label="Enter a name" placeholder="Michel" v-model="currentName"></v-text-field>
        <p>My name is {{ currentName }}</p>
        <chipButton @click="addChip( currentName )"></chipButton>
    </div>
</template>

<script>
import chipButton from './button.vue';

export default {
    data: () => ({
        currentName: ""
    }),
    components: {
        chipButton,
    },
    methods: {
        addChip: function(name) {
            console.log(name);
            let actualChips = document.getElementById('chips');
            let newChip = document.createElement('customChip');
            newChip.name = name;
            actualChips.appendChild('newChip');
        }
    }
}
</script>

Answer №1

To capture the click event on the HTML element of the chipButton component, opt for @click.native= instead of @click= to register events on the native element rather than the component itself.

If it's necessary to monitor the click event on the component, you must emit that event from the component (similar to when the event listener is on a child element):

// chipComponent.vue
<template>
  <div>
    <button @click="$emit('click')">Something</button>
  </div>
</template>

However, using the @click.native= directive is recommended unless there are specific requirements.

Answer №2

Every instance of the template tag <chipButton> has been replaced with its contents. For example, if you use

<chipButton @click="addChip( currentName )">
, it will be replaced with the template content and any other attributes will disappear.

Here is an example to clarify the concept mentioned above.

Vue.component('test',{
  template:`<div @click="childClick">Click here to see which method is being called</div>`,
  methods:{
    childClick: function(){
      alert('childClick');
    }
  }
})
var app = new Vue({
  el:'#niklesh',
  data:{
    name:'Niklesh Raut'
  },
  methods:{
    parentClick: function(){
      alert('parentClick');
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="niklesh">
  <test  @click="parentClick"></test>
</div>

Solution 1 : You can place your method inside the child component.

Solution 2 : Alternatively, you can wrap it with a tag like div.

Vue.component('test',{
  template:`<div @click="childClick">Click here to see which method is being called</div>`,
  methods:{
    childClick: function(){
      alert('childClick');
    }
  }
})
var app = new Vue({
  el:'#niklesh',
  data:{
    name:'Niklesh Raut'
  },
  methods:{
    parentClick: function(){
      alert('parentClick');
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="niklesh">
  <div @click="parentClick"><test></test></div>
</div>

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

Creating a dynamic routerLink value in Angular 8 for items within an ngFor loop

I am currently attempting to route a dynamic value from the NgFor using [routerLink]. <li class="list-group-item d-flex justify-content-between align-items-center" *ngFor="let factors of factorsList"> <span>{{factors | ...

What is the best way to minify and concatenate multiple CSS files only after converting SCSS to CSS with Gulp?

When attempting to convert my scss files to css files using gulp, I encountered an issue. After writing the scss code, it is easily converted to css. However, I wanted to minify this css and save it in a different folder called 'min'. Within the ...

Adjust the size of every card in a row when one card is resized

At the top of the page, I have four cards that are visible. Each card's height adjusts based on its content and will resize when the window size is changed. My goal is to ensure that all cards in the same row have equal heights. To see a demo, visit: ...

Specialized hover mission

Do you have a question? Imagine you have 3 spans where the default color is black. When you hover over a span, its color changes to red. But what if I told you that at the start, the first span has an orange color. Now, I want to hover over the orange on ...

jQuery UI dynamically adjusting content layout based on browser size changes

Having an issue with my custom accordion script where resizing the browser causes formatting problems in one of the sections. I want the content to remain intact and to utilize a scrollbar if necessary to view the content. The problem is visible in section ...

Angularjs 2 Error: Unable to access the 'infos' property of an undefined object using the Http Client

I've been working on an AngularJS app for about a week now, developing a backoffice application for my service. My main challenge lies in using data retrieved from a remote server. I have 4 HTTP GET requests in my app - 2 of them fetching lists of us ...

Searching strings with regex

I am working with a specific string of text that I want to replace within a given div. Here's how I know to do it: myelement.replace(/foo/g, 'bar'); But what if I need to use my own string instead of the fixed text "foo"? myelement.replac ...

What is the best method for choosing one specific item from an array within a data object and transferring it to a different component?

After retrieving data using axios and passing it to a Bootstrap table, I have set up a click event in my computed properties for the nameOfPerson field. This event allows users to click on a person's name and open a modal that displays the correspondi ...

What steps can I take to ensure that my bot disregards any actions taken by other bots?

I need assistance with configuring my bot to ignore certain actions by other bots and prevent logging them. Below is the snippet of my code: let messagechannel = oldMember.guild.channels.find(r => r.name === config.logsChannel); if (!messagecha ...

Guide to rendering JavaScript with pug/jade

Let's say I pass the user variable to this Pug file and I'd like to execute some JavaScript code after the DOM has finished loading. script. document.addEventListener("DOMContentLoaded", function(event) { console.log(#{user.name});/ ...

Is there a way to circumvent the mouse up event?

I want to create a feature where when a user clicks down, something specific occurs. The sequence of events includes: An action taking place (which is not the focus here). Triggering a mouse up event. Implemented with: angular, html, css. Excludes: jQue ...

How come the variable is not being passed to the HTML article within the function?

I'm struggling to pass a variable from a function to an article. Despite successfully displaying the variable in an alert box, I can't seem to get it to show up in the article content. What am I missing? After confirming that "a" contains the co ...

VueJS - Harnessing the power of the Document Object Model for dynamic template rendering

Essentially, I am in need of VueJS to provide warnings for unregistered components when in DOM template parsing mode. It seems that currently Vue does not pay attention to custom HTML when using DOM templates, although errors are correctly displayed with s ...

React Href is not functioning as expected in relative paths

Recently, I delved into React apps and managed to create one with a router. Everything was smooth sailing in dev mode until I tried running index.html from the build folder after npm run build. It seems like all the href links are broken. I suspect somethi ...

After clicking the Nuxt JS button, the response instantly pops up

Is it possible to conceal the responses of a Nuxt js project and post requests with SSR initially? During the initial page load, this can be achieved. <template> <p v-if="$fetchState.pending">Fetching mountains...</p> & ...

Tips for sending an object in AngularJS to the HTTPOST method

I am facing an issue where I am trying to pass an object to my controller using the $http method, but even though the object has a value, the data being passed is showing as NULL. Below is the code snippet that demonstrates this problem. Within my JavaScr ...

Implementing interactive functionality to expanding lists in Vuetify.js

Can someone help me figure out how to add an active state for lists in Vuetify? I want the lists to have a primary background color, just like they show in their documentation: This is my code: <template> <v-navigation-drawer width="300px& ...

create a word with only **one** bold letter in the word ionic-angularjs

Can someone please guide me on how to style only a specific letter within a word using angularJS? Specifically, I want to make the first letter bold while keeping the rest of the word in normal font. For instance, if I have an array of words like: var Wor ...

Set Covering: Identify an array combination that intersects with all elements of a specified target array

Suppose there is an array, A, which can be sorted if that information helps. We have multiple arrays, B, C, D, etc., all sortable and potentially overlapping with array A. The objective is to identify the smallest combination of arrays B, C, D, etc., whi ...

Is it possible to have a text box that is partially read-only and partially editable?

<form> <div class="col-sm-2" style="margin-top: 5px;color:#357EBD;font-weight:bold;" id="sub-ticketid"><?php echo 'Ticket 12345#'; ?></div> <input type="text" class="form-control" style="background:#fff;" name="sub-hold ...