Vue should only activate the element that has been clicked on

I'm currently working on my first Vue project and encountering an issue with triggering a child component within a table cell. Whenever I double click a cell, the `updated` event is being triggered in all child components associated with the table cells instead of just the one I clicked on.

My current approach involves passing props to the child component, which does work. However, the problem arises when multiple child components are activated unnecessarily due to the propagation of the `updated` event.

Screenshot

https://i.sstatic.net/CQjxX.png

Code and question

The code snippet below may not reflect the exact structure of my project but showcases the mentioned issue. Clicking on a button triggers actions for all cells rather than just the targeted cell:

While I understand why this happens - as each child component reacts to updated data from the parent - it's unnecessary for inactive child components to be triggered. How can I ensure that only the `updated` event of the clicked item is triggered?

Vue.component('v-child', {
  props: ['item', 'active'],
  updated() {
    console.log('Clicked');
  },
  template: `
  <div>
      {{ item }} {{ active }}
  </div>`
  });

new Vue({
  el: '#app',
  data: {
    active: 0,
  items: {
    first: '1',
      second: '2',
      third: '3',
      a: 'a',
      b: 'b',
      c: 'c'
    },
    message: 'Hello Vue.js!'
  },
  methods: {
  click(item) {
      this.active = item;
      console.log(this.active);
    }
  }
});
li {
  list-style: none;
  margin-bottom: 1rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
    <li v-for="item in items">
      <button v-on:click="click(item)">Button</button>
      <v-child :item="item" :active="active"></v-child>
    </li>
  </div>

Answer №1

refreshed is invoked on every child element because there has been a change in active, prompting the rendering of each child.

There are two methods to achieve your desired outcome:

  • Alter active to only modify the active item
  • Maintain your current code and implement checks to determine if the child is active (as per Steven Spungin's suggestion)

Example for solution #1

Vue.component('v-child', {
  props: ['item', 'active'],
  updated() {
    console.log('Clicked');
  },
  template: `
  <div>
      {{ item.value }} {{ item.count }}
  </div>`
});

new Vue({
  el: '#app',
  data: {
    active: 0,
    items: {
      first: {value:'1', count:0},
      second: {value:'2', count:0},
      third: {value:'3', count:0},
      a: {value:'a', count:0},
      b: {value:'b', count:0},
      c: {value:'c', count:0}
    },
    message: 'Hello Vue.js!'
  },
  methods: {
    click(item) {
      item.count++;
    }
  }
});
li {
  list-style: none;
  margin-bottom: 1rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <li v-for="item in items">
    <button v-on:click="click(item)">Button</button>
    <v-child :item="item" :active="active"></v-child>
  </li>
</div>

Answer №2

Include a watch hook for the active property and compare its value with the item property.

Vue.component('v-child', {
  props: ['item', 'active'],
  watch: {
    active(value) {
      if (value === this.item) {
        console.log('Clicked:' + value);
      }
    }
  },
  template: `
  <div>
      {{ item }} {{ active }}
  </div>`
});

new Vue({
  el: '#app',
  data: {
    active: 0,
    items: {
      first: '1',
      second: '2',
      third: '3',
      a: 'a',
      b: 'b',
      c: 'c'
    },
    message: 'Hello Vue.js!'
  },
  methods: {
    click(item) {
      this.active = item;
    }
  }
});
li {
  list-style: none;
  margin-bottom: 1rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <li v-for="item in items">
    <button v-on:click="click(item)">Button</button>
    <v-child :item="item" :active="active"></v-child>
  </li>
</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

Using AJAX autocomplete with Sys.Serialization.JavaScriptSerializer

I implemented an ajax autocomplete feature in ASP.NET where a method from a web service is called to fetch postal codes. public string[] GetNames(string prefixText, int count, String contextKey) { prefixText = prefixText.Trim(); XmlNodeList list; ...

JavaScript allows for the manipulation of elements within a webpage, which includes accessing elements from one

There is a file that contains a fragment for the navbar. The idea is to have listItems in the navbar, and upon clicking on those listItems, another subnavigationbar should open below it. Below is the code I currently have: <!DOCTYPE html> <html x ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...

Experience the frustration when the Ruby on Rails Open Modal Box Link fails to work. Stay tuned for the latest update on the link

My goal is to have a Modal Popup Box open when a specific link is clicked on my page. Here is the code I added to my view file: <%= link_to_remote '+ Add Discount', :url => {:controller => "parent_wise_fee_payments", :action => "ne ...

Utilizing the `this` keyword within a click handler that is passed through an intermediary function

If I initially have a click event handler in jQuery set up like this jQuery('#btn').click(_eventHandler); And handling the event as follows function _eventHandler(e){ jQuery(this).text('Clicked'); } Does the this keyword serve a ...

Saving information in node.js

My latest project involves creating an address book app using HTML, CSS, and JavaScript. The company provided me with a zip file containing the necessary resources to implement the app using node.js. However, my knowledge of node.js is limited and I have ...

The key up event in JQuery does not seem to be triggered when selecting the second option in the Select2 plugin's multi

Encountered an issue with the select2 plugin while trying to change the option list based on user input for the second multiple option. The first time I enter text in the multi-select field, the keyup event is triggered and an ajax function is called to b ...

The JSON.Parse function in Google Apps Script is leading to a 'server connection error' message during debugging

I'm not a professional developer, but I do code occasionally. Currently, I am working on some Apps Script code to interact with an API and store the data in SQL. Most of it is working fine, but I have encountered an issue while debugging in the Apps S ...

The animation in Material UI does not smoothly transition with the webkit scrollbar

I've been experimenting with CSS animations in Material UI's sx property to achieve a webkit scrollbar that eases in and out. However, instead of the desired effect, the scrollbar appears and disappears instantly. Whether I define the keyframes ...

Vue's unshift method only appends new items to the beginning of an

Could you help me with a problem similar to this one: The array I am working with looks like this: remate: {id:1, lotes: [{id:1, nombre: lalala}, {id:2, nombre: lololo}]} My issue arises when attempting to add new items to remate.lotes. While the push m ...

What is the best way to merge 60 related jquery functions into a unified function?

I designed a webpage that serves as an extensive checklist. When you click on the edit button for a checklist item, a modal window opens up. This modal window contains a radio button to indicate whether any issues were found during the check. If "Yes" is s ...

Changing an Array into JSON format using AngularJS

I am attempting to switch from a dropdown to a multiselect dropdown. <select name="molecularMethod" class="form-control" ng-model="request.molecularMethod" multiple> It is functioning properly. However, when items are selected, it generates an arra ...

How to calculate the difference in months between two dates using JavaScript

Is there a way to calculate the number of months between two dates taking into account specific conditions, such as when the dates are not exact and may have different day counts? Here is an example using the moment library: var date1 = moment('202 ...

What is the alternative to using this.$parent.$emit in Vue 3?

Recently, my application has been upgraded to Vue 3. Following the migration, my linter flagged a deprecation error that is documented at this link: . The documentation provides guidance on replacing this.$emit with the mitt library, however, it does not ...

Unable to retrieve the JSON response item

Currently, I am in the process of setting up an AJAX call with the intention of manipulating the response data. Upon inspecting my browser's network console, this is the response I am seeing: { "message": "success", "file": "dump.xml" } Thi ...

Utilizing Jquery's each() method to retrieve the exact position of a specific class element

Is there a way to determine the position of the "owl-item active" element? The current position is 2 out of 3 total photos. <div style="transform: translate3d(-825px, 0px, 0px); transition: all 0.25s ease 0s; width: 48675px;" class="owl-stage"> ...

Can anyone provide guidance on showcasing data received from Laravel resource in a Vue Component?

I've been honing my skills in Vue and am grappling with how to manage data passing. Within my Vue component, I have a link that looks like this: <a class="btn btn-success" :href="'/projectpage/' + project.id">Bid</a>, and I found ...

Click the button to access the login form created using React components

I have been working on developing a login form that includes various input components and a button component. SignIn.js class SignIn extends Component { render() { return ( <article className="br2 ba dark-gray b--black-10 mv4 w-100 w-50-m ...

I have implemented a custom-built sidebar component and I'm unsure about the process of adding data to it

After successfully incorporating this SideBar into my Vuex/Laravel project, I encountered a problem. The example code provided used: <div :class="$style.sidebar"/> However, when I tried to modify it to: <div :class="$style.sidebar">Content&l ...

AngularJS: splitting the parent <div> into multiple sections every nth element

I have an array of strings in Javascript and I am attempting to use AngularJS to create nested <div> elements. var arr = ["abc", "def", "ghi", "jkl", "mno", "pqr", "stu"]; My goal is to group every 3 elements together like so. <div class="pare ...