Tips for passing a reference through an event bus in order to successfully set it as null

I'm delving into Vue2 and hoping to create a reusable selected-item component. My goal is to have this component reference an item that can trigger a message on an event bus to reset the item to null. This marks my first experience working with Vue not in a single-file-component / .vue file setup.

Below is the code snippet where I've encountered some issues:

var bus = new Vue()

Vue.component('selected-item', {
  props: ['item'], 
  methods: {
    setToNull(item){
      bus.$emit('setToNull', item);
    }
  },
  template: `<span>
               <div class="button round btn-app-class selected-btn">{{item.name}}<sup><span class='btn-delete link' @click="setToNull(item)">x</span></sup></div>
             </span>   
            `
})

var vm = new Vue({
  template:`
      <div>
        <div v-if="selectedApp">
           <selected-item :item="selectedApp"></selected-item>
        </div>
        <div v-else>
          no app selected
        </div>
      </div>
   `,
    data(){
      return {
        selectedApp: {id: 1, name: 'here is my name'}
      }
    },
    mounted(){
     bus.$on('setToNull', function (item) {
      alert('within setToNull for: ' + item.name); // this works and outputs here is my name 
      item = null; // this doesn't work
    })

    }
})    

What could be causing this issue? Is there a more efficient approach to achieving this functionality?

edit #1

It seems like directly setting selectedApp within the emitted event is effective! I've also cleaned up the code by removing the event bus and extraneous parts. Here's the updated implementation:

      <selected-item @remove="selectedApp = null" :item="selectedApp"></selected-item>

https://jsfiddle.net/qnub8xen/

Answer №1

To clear the value, you should assign null to this.selectedApp

mounted(){
 bus.$on('clearValue', function (item) {
  alert('Executing clearValue for: ' + item.name);
  this.selectedApp = null;
})

Answer №2

provide an illustration

'use strict'
const bus = new Vue;

const selectedOption = {
  template: '#selectedOptionTpl',
  props: ['option'],
  methods: {
    setToEmpty(option) {
      bus.$emit('remove-option', option);
    }
  }
}

var application = new Vue({
  el: '#application',
  components: {selectedOption},
  data (){
    return {
      selectedOptions: new Array(5).fill('').map((o,i)=>({id:i,name:'option-'+i}))
    }
  },
  created () {
    bus.$on('remove-option',option=>{
      let options = this.selectedOptions;
      for(let i=0;i<options.length;i++){
        if(option.id==options[i].id){
          options.splice(i,1)
          break;
        }
      }
    })
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="application">
<div v-for="option in selectedOptions" :key="option.id">
<selected-option :option="option"></selected-option>
</div>
</div>

<script id="selectedOptionTpl" type="text/x-template">
<span>
<div class="button round btn-app-class selected-btn">{{option.name}}<sup><span class='btn-delete link' @click="setToEmpty(option)">x</span></sup></div>
</span>
</script>

Answer №3

Utilizing a callback style in place of an event bus allows for the reusability of your component multiple times. Here's an illustration:

Vue.component('selected-item', {
  props: ['item', 'callback', 'objName'], 
  methods: {
    setToNull() {
      this.callback(this.objName);
    }
  },
  template: `
    <div v-if="item && item.name">
      <div class="button round btn-app-class selected-btn">
        {{item.name}}
        <span class='btn-delete link' @click="setToNull">x</span>
      </div>
    </div>
  `
})

var vm = new Vue({
  el: '#app',
  template:
  `
  <div>
     <div>
    <selected-item 
          :item="selectedApp"
            :callback="callback"
            :objName="'selectedApp'"
        />
        <selected-item 
          :item="selectedApp2"
            :callback="callback"
            :objName="'selectedApp2'"
        />
        <selected-item 
          :item="selectedApp3"
            :callback="callback"
            :objName="'selectedApp3'"
        />
    </div>
    <div v-else>
    no app selected
    </div>
  </div>
 `,
 data() {
     return {
        selectedApp: {id: 1, name: 'here is my name1'},
        selectedApp2: {id: 2, name: 'here is my name2'},
        selectedApp3: {id: 1, name: 'here is my name3'}
     }
 },
 methods: {
 callback(objName) {
        console.log('object name received on callback ' + objName);
        this[objName] = null;
        console.log('clean value from local parent state');
        console.log(this[objName]);
    }
 }
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app" />

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

Issue: "fourSquareService.retrieveLocations does not exist as a function"

Struggling with AngularJs - How to Utilize Factory Alongside Form Input in URL for Data Fetching? This is my first time asking a question here. I've been diving into Angular and wanted to organize my services by separating them into different files. ...

Anchor tags created using JQuery will remain on the same page without redirecting

Presented below is the code I have utilized to construct the anchor tag along with its content. $('div#right-slide').html("<a href=\"http://www.XXXXXXXXXXXX.info/limited-specials/\" ><h1 id=\"specials\">Click Here ...

What does the underscore before a function in JavaScript or PHP signify?

I am curious about the significance of the underscore symbol (_) when it is placed before a function or variable. Does it serve to simply describe something, or is it required for executing specific functions or calling certain methods? In JavaScript: va ...

Ways to verify if the scroll bar of a user is not visible

Is there a method to detect if the user has forcibly hidden the scroll bar in the operating system? 1. Automatically based on mouse or trackpad 2. Always 3. When scrolling I want to adjust the width of an HTML element if the scroll bar is visible, which c ...

The Proper Way to Include External CSS in a Next.js Page Without Triggering Any Warnings

I find myself in a scenario where I must dynamically inject CSS into a webpage. The content of this page is constantly changing, and I am provided with raw HTML and a link to a CSS file from a server that needs to be displayed on the page. My attempt to ...

Retrieving selective attributes from Cosmos DB NoSQL using NodeJS/Javascript: Exploring the readAll() method for retrieving specific attributes instead of the entire object

Imagine having the following set of documents in your Cosmos DB (NoSQL) container: [ { "id": "isaacnewton", "fullname": "Isaac Newton", "dob": "04011643", "country": &q ...

Exploring methods to retrieve data from an array in a Vue store through Getters

I am currently facing an issue where I am attempting to include an argument within getters in order to retrieve the ID of the permissions, but unfortunately it is not returning any results. ////STATE state: { permissions: [ {id: 1, name: 'Crea ...

Convert an HTML table with a drop-down menu into a CSV file for exporting

My table has the capability for users to add additional columns, with each new column containing a dropdown list option. However, when attempting to export the table as a CSV file, I encountered an issue where the export functionality only works properly o ...

PHP cannot be utilized within the script tag

I'm currently using JavaScript to display an error message If a user inputs incorrect information and I add the following code: <?php $_POST["usernamereg"] ?> = usernamereg; the alert function stops working. However, if I remove this code, t ...

Initiating a request to the "/login" endpoint using Vue.js

Below is the login template I have created for sending a POST request to my Java SpringBoot application: <template> <div div="login"> <div class="login-form"> <b-card title="Login" ...

Clickable list element with a button on top

Within my web application, there is a list displaying options for the user. Each 'li' element within this list is clickable, allowing the user to navigate to their selected option. Additionally, every 'li' element contains two buttons - ...

What is the best way to create a "read-more" button for multiple text sections?

I have a collection of unique artwork displayed on my website, each accompanied by a brief description. <div> <h2>Emotions in Motion</h2> <p> This piece is a captivating blend of vibrant colors and intricate details ...

I am experiencing issues with my JavaScript not functioning properly in conjunction with my HTML and CSS. I am uncertain about the root cause of the problem (The console is displaying an error message:

I am facing challenges in creating a content slider and encountering issues with its functionality. Specifically, when testing locally, I noticed that the current-slide fades out and back in upon clicking the arrows left or right, but the slide content is ...

What is the method of instantiating a Selenium WebDriver instance in Node.js without initializing the browser?

Is there a way to create an instance of the selenium webdriver without launching a new browser every time? I want to keep the driver in a common place and prevent a new browser from opening with each call. The code below shows how I am currently creating a ...

Organize the dataset into groups based on every possible key

Hi there, I'm facing a challenge while developing an application using NestJS/Prisma. The task at hand is to extract unique results from a table in order to display them in a filter on the front-end. Let me give you an overview of my table structure ...

Retrieving Information from Website Components in JavaFX Web View

I am currently developing a Java FX program that loads a folder containing HTML/CSS/JS files with 3 different websites. While the websites are displaying correctly in the webview, I am looking for a way to capture user interactions, such as checkbox selec ...

Utilizing HighChart in ASP.NET MVC for Dynamic Data Visualization from a Database

I am completely new to ASP.NET MVC and I am trying to show data from a database in a Highchart using Visual Studio 2015. In my controller, I have the following code to retrieve data from the database: namespace HelloWorld.Controllers { public class Se ...

Ensure that the loop is fully executed before proceeding with any additional code

Check out this code snippet I've been developing: let arrayB = []; for (let index = 0; index < res.length; index++) { let fooFound = false; const dynamicFoo = require(`./modules/${res[index]}`); rest.get(Routes.applicationCommands("BLA ...

I am unable to invoke a JavaScript function from PHP code

Please Note: Despite all my efforts, I have been unable to find a solution to this issue. I have scoured numerous online resources, including Stack Overflow, without success. Surprisingly, I could not locate a relevant question on Stack Overflow addressing ...

How can I deactivate all form controls within an AngularJS form?

To prevent any changes to the form components when the view button is clicked, I need to disable them. Here is my form: <form action="#" class="form-horizontal" > <div class="form-group"> <label for="fieldname" class="col-md-3 cont ...