The reactivity of a Vue.js computed property diminishes when it is transmitted through an event handler

Within my main application, I've implemented a Modal component that receives content via an event whenever a modal needs to be displayed. The Modal content consists of a list with an associated action for each item, such as "select" or "remove":

Vue.component('modal', {
  data() {
    return {
      shown: false,
      items: [],
      callback: ()=>{}
    }
  },
  mounted() {
    EventBus.$on('showModal', this.show);
  },
  template: `<ul v-if="shown">
    <li v-for="item in items">
      {{ item }} <button @click="callback(item)">Remove</button>
    </li>
  </ul>`,
  methods: {
    show(items, callback) {
      this.shown = true;
      this.items = items;
      this.callback = callback;
    }
  }
});

However, when passing a computed property to the modal like in the following component, the reactive connection is lost -> causing the list not to update if the action is "remove".

Vue.component('comp', {
  data() {
    return {obj: {a: 'foo', b: 'bar'}}
  },
  computed: {
    objKeys() {
      return Object.keys(this.obj);
    }
  },
  template: `<div>
    <button @click="showModal">Show Modal</button>
    <modal></modal>
  </div>`,
  methods: {
    remove(name) {
      this.$delete(this.obj, name);
    },
    showModal() {
      EventBus.$emit('showModal', this.objKeys, this.remove);
    }
  }
});

You can view the minimal use case on this fiddle: https://jsfiddle.net/christophfriedrich/cm778wgj/14/

I suspect there might be a bug - shouldn't Vue recognize that objKeys is used in the rendering of Modal and update it accordingly? (The propagation of changes from obj to objKeys functions correctly.) If not, what am I missing and how can I achieve the desired outcome?

Answer №1

The modal functionality is now operational with its own distinct set of items:

 template: `<ul v-if="shown">
    <li v-for="item in items">
      {{ item }} <button @click="callback(item)">Remove</button>
    </li>
  </ul>`,
  methods: {
    show(items, callback) {
      this.shown = true;
      this.items = items;
      this.callback = callback;
    }
  }

This independent copy is generated once, upon invoking the show method, and what you are duplicating is simply the value computed at the time you trigger the showModal event. What gets passed to show is not a computation, and what it assigns is not one either. It's merely a value.

If at any point within your codebase, you executed an assignment like

someDataItem = someComputed;

The data item would not mirror the computed function but rather represent a snapshot of its value at the assignation moment. This elucidates why transferring values around in Vue is ill-advised: they do not inherently synchronize.

Instead of relocating values back and forth, you can utilize a function that retrieves the desired value - essentially acting as a getter function. For enhanced readability, you may formulate a computed property predicated on said function. Subsequently, your script transforms into:

const EventBus = new Vue();

Vue.component('comp', {
  data() {
    return {
      obj: {
        a: 'foo',
        b: 'bar'
      }
    }
  },
  computed: {
    objKeys() {
      return Object.keys(this.obj);
    }
  },
  template: `<div>
    <div>Entire object: {{ obj }}</div>
    <div>Just the keys: {{ objKeys }}</div>
    <button @click="remove('a')">Remove a</button>
    <button @click="remove('b')">Remove b</button>
    <button @click="showModal">Show Modal</button>
    <modal></modal>
  </div>`,
  methods: {
    remove(name) {
      this.$delete(this.obj, name);
    },
    showModal() {
      EventBus.$emit('showModal', () => this.objKeys, this.remove);
    }
  }
});

Vue.component('modal', {
  data() {
    return {
      shown: false,
      getItems: null,
      callback: () => {}
    }
  },
  mounted() {
    EventBus.$on('showModal', this.show);
  },
  template: `<div v-if="shown">
  <ul v-if="items.length>0">
    <li v-for="item in items">
      {{ item }} <button @click="callback(item)">Remove</button>
    </li>
  </ul>
  <em v-else>empty</em>
</div>`,
  computed: {
    items() {
      return this.getItems && this.getItems();
    }
  },
  methods: {
    show(getItems, callback) {
      this.shown = true;
      this.getItems = getItems;
      this.callback = callback;
    }
  }
});

var app = new Vue({
  el: '#app'
})
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <comp></comp>
</div>

Answer №2

When you pass a value to a function, it's not the same as passing a prop to a component. Props are reactive because they trigger changes, whereas values remain static. If you want reactivity, make sure to include items as a prop in the template of your comp component.

Instead of using callbacks, consider implementing a process where events are emitted and handled in the parent component for removing items.

const EventBus = new Vue();

Vue.component('comp', {
  data() {
    return {
      obj: {
        a: 'foo',
        b: 'bar'
      }
    }
  },
  computed: {
    objKeys() {
      return Object.keys(this.obj);
    }
  },
  template: `<div>
    <div>Entire object: {{ obj }}</div>
    <div>Just the keys: {{ objKeys }}</div>
    <button @click="remove('a')">Remove a</button>
    <button @click="remove('b')">Remove b</button>
    <button @click="showModal">Show Modal</button>
    <modal :items="objKeys" event-name="remove" @remove="remove"></modal>
  </div>`,
  methods: {
    remove(name) {
      this.$delete(this.obj, name);
    },
    showModal() {
      EventBus.$emit('showModal');
    }
  }
});

Vue.component('modal', {
  props: ['items', 'eventName'],
  data() {
    return {
      shown: false,
    }
  },
  mounted() {
    EventBus.$on('showModal', this.show);
  },
  template: `<div v-if="shown">
  <ul v-if="items.length>0">
    <li v-for="item in items">
      {{ item }} <button @click="emitEvent(item)">Remove</button>
    </li>
  </ul>
  <em v-else>empty</em>
</div>`,
  methods: {
    show(items, callback) {
      this.shown = true;
    },
    emitEvent(item) {
      this.$emit(this.eventName, item);
    }
  }
});

var app = new Vue({
  el: '#app'
})
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <comp></comp>
</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

The native javascript modal fails to appear

I'm attempting to implement the functionality from this Codepen demo into my project. I've copied over the HTML, CSS, and JavaScript code: <!DOCTYPE HTML> <html> <head> <script> var dialog = docume ...

The correct terminology for divs, spans, paragraphs, images, anchor tags, table rows, table data, unordered lists, list

Just wondering, I've noticed that every time I come across a page element '<###>[content]<###>' and want to learn how to manipulate it, I usually search for something like "how to do x with div" or "how to get y from div". I know that ...

Exchanging data between dynamic child components

As a newcomer to vuejs, I've encountered an issue with my parent component and its child components. The children swap in and out using <component :is="view">, where the view is a property of the parent component. Each child component needs to b ...

Node Signature Generation for Gigya Comment Notifications

I am currently using the Gigya Comment Notification service within my node application and attempting to generate a valid signature. Despite following the documentation, my code is producing an incorrect hash. Below is the code I am using: var crypto = r ...

`How can a child component in Next.js send updated data to its parent component?`

Currently diving into Next.js and tinkering with a little project. My setup includes a Canvas component alongside a child component named Preview. Within the Preview component, I'm tweaking data from the parent (Canvas) to yield a fresh outcome. The b ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

Extracting data from XPath results reveals information beyond just the elements themselves

Having trouble using the getElementsByXPath function in CasperJS to return a specific string from an xpath I determined. Despite my efforts, it seems like the function is only returning data for the entire webpage instead of the desired string. var casper ...

Twitter API causing issues with setTimeout function in Node.js

Attempting to read from a file and tweet the contents in 140 character chunks, one after the other has proven to be quite challenging. Despite verifying that other parts of the code are functioning correctly, using a simple for-loop resulted in tweets bein ...

Set up npm and package at the main directory of a web application

Currently, I am in the process of developing a web application using node.js. Within my project structure, I have segregated the front-end code into a 'client' folder and all back-end logic into a 'server' folder. My question revolves a ...

Resizing svg to accommodate a circle shape

As I work on my vue.js app that involves a plethora of diverse icons, I made the decision to create a small icons builder in node.js. The purpose is to standardize their usage and also "crop" each SVG so it fits perfectly within its parent container by uti ...

Navigating through a series of items in VueJS can be easily accomplished by using a

Below is the Vue instance I have created: new Vue({ el: '#app', data: { showPerson: true, persons: [ {id: 1, name: 'Alice'}, {id: 2, name: 'Barbara'}, {id: 3, name: &a ...

Experiencing difficulty when attempting to save a zip file to the C drive

I came across this code snippet on SO and decided to use it for my project. The goal is to send a simple 1.5mb zip file and save it on my C drive by making a request through Postman with the binary option enabled, sending the zip file to localhost:3012. c ...

The issue of calling the child window function from the parent window upon clicking does not seem to be functioning properly on Safari and Chrome

I'm attempting to invoke the function of a child window from the parent window when a click event occurs. Strangely, this code works in Firefox but not in Safari or Chrome. Here is the code snippet I am using: var iframeElem = document.getElementById( ...

What is the best method for enabling HTML tags when using the TinyMCE paste plugin?

After spending countless hours searching for a solution, I am still puzzled by this problem. My ultimate goal is to have two modes in my powerful TinyMCE editor: Allowing the pasting of HTML or Word/OpenOffice text with all styles and formatting attribu ...

Failure to send Websocket connection

Currently working on PHP, here's a snippet: $room_array = array(); $room_array[0] = 'room-list'; $room_array['info'] = array('room_name' => $room['room_name'], 'owner' => $username['usernam ...

Trick to keep horizontal element alignment intact when scroll bar appears

Currently, all my pages are designed with the standard fixed-width-margin-left-right-auto layout. .container{ width:900px; margin:0 auto; } An issue arises when some of these pages exceed the height of the window, requiring a vertical scroll ba ...

Steps to deactivate a individual v-expansion-header

(I am working with Vue 2.6) - I have been exploring the v-expansion-panels in Vuetify and came across the disabled property in the documentation. However, setting it disables the entire v-expansion-panel, whereas I need to disable individual occurrences ...

Adjust the pagination length within the jQuery DataTables plug-in

I am looking to customize the pagination length in DataTables plug-in for jQuery. Specifically, I want to calculate the number of pages on the server side and display the correct amount of buttons on the client side. Can anyone provide guidance on how to ...

The $.inArray() function returns a value of false or -1, despite the fact that the variable

My goal is to verify that my currentMedia variable (which exists in the DOM) can be located within my array media, and then return the index i, which should be 0 instead of -1. When I execute console.log(media[0]); and console.log(currentMedia);, the outc ...

Tips on integrating Codrops tutorial codes into a SilverStripe website project

Exploring the vast array of tutorials and code examples on the Codrops site has been an enlightening experience. Codrops Website I'm eager to incorporate some of these resources into my SilverStripe projects as well. SilverStripe CMS After learning h ...