Updating the model of a Vuejs single file component (.vue) within the <script> tag

Discovering the world of vuejs, I set out to create a basic single file component for testing purposes.

This component's main task is to showcase a boolean and a button that toggles the boolean value. It also listens for a "customEvent" which triggers another change in the boolean value.

<template>
  {{ mybool }}
  <button v-on:click="test">test</button>
</template>

<script>    
  ipcRenderer.on('customEvent', () => {
    console.log('event received');
    this.mybool = !this.mybool;
  });


  export default {
    data() {
      return {
        mybool: true,
      };
    },
    methods: {
      test: () => {
        console.log(mybool);
        mybool = !mybool;
      },
    },
  };
</script>

The button behaves as expected - clicking it results in a value change. However, when the event is triggered, 'event received' is logged to the console but the boolean remains unchanged.

I'm wondering if there's a way to access the component's data from my code.

Appreciate your help, Eric

Answer №2

Make sure to set up the event listener within the component's options block that you export using:

export default{ //... options }

By placing the event listener inside the vue options, the vue instance will have control over it, allowing you to modify your data property as needed

Following choasia's advice, move the event listener to the `created()` lifecycle hook:

<template>
  {{ mybool }}
  <button v-on:click="test">test</button>
</template>

<script>    

  export default {
    data() {
      return {
        mybool: true,
      };
    },
    methods: {
      test: () => {
        console.log(mybool);
        mybool = !mybool;
      },
    },
    created(){
        ipcRenderer.on('customEvent', () => {
            console.log('event received');
            this.mybool = !this.mybool;
        });
    }
  };
</script> 

Your component will now listen for the specified event when it is created

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

Encountering a null value after making changes to the state in Reactjs

I'm currently working on a drag-and-drop web application using reactjs. The issue I'm encountering is that when I initiate the drag action, it triggers the handleDragStart function to update the state variable called selectedCard. However, when I ...

Having trouble updating the sequelize-cli configuration to a dynamic configuration

Encountering an issue while attempting to switch the sequelize-cli configuration to dynamic configuration, following the instructions in the documentation. I have created the .sequelizerc-file in the project's root directory and set up the path to con ...

Dealing with Oversized Images in Jcrop: Tips and Tricks

Utilizing Jcrop for cropping images, everything runs smoothly with small images. However, when I attempt to use large images like 2080x2080 or 1600x1600, it takes up the entire screen and cannot be controlled by CSS properties such as width and height in t ...

The meaning gets blurred when using 'this' in a prototype method

Alright, so I am working on a node application that utilizes express. In this particular application, there's an express route set up like this: var MyObject = require('./myObject') , myObject = new MyObject(); app.post('/api/w ...

Learn how to showcase real-time stock information from Yahoo Finance on an Android device. See the JSON format provided below for guidance

finance_charts_json_callback( { "meta" : { "uri" :"/instrument/1.0/PTC/chartdata;type=quote;range=1d/json/", "ticker" : "ptc", "Company-Name" : "PTC Inc.", "Exchange-Name" : "NMS", "unit" : "MIN", "timezone" : "EDT", "curr ...

Utilize AngularJS to bind keys to arrays

Hey there, I have an array that looks like this: $scope.Selectedgroups =[183,184,24] I want to convert it to the format shown below: [{groupId:183},{groupId:184},{groupId:24}]; I've been trying to convert it using a for loop: var groups=[] ...

Click on the button to be directed to a different page using React

<div class="clickable-icon"> <button component={Link} to={"/create"}> <EditIcon></EditIcon> </button> </div> I have written this code snippet to turn an icon into a clickable button that directs ...

Unsure if values can be imported from one component to another in Vue.js using props

Currently experimenting with Vue and ran into a minor challenge - wondering if there's a solution to this. I am looking to add a new value to my items array using my Button component so that I can display it using v-for. While consolidating everything ...

Organize database entries by categories for easy navigation

I've developed a web application centered around TV Shows to enhance my understanding of AngularJS. Within my database, I have a table containing various TV shows, each with an assigned category column. For instance, "Dexter" is categorized as "thrill ...

XMLHttpRequest response: the connection has been terminated

After developing a Flickr search engine, I encountered an issue where the call to the public feed or FlickrApi varies depending on the selection made in a drop-down box. The JSONP function calls provide examples of the returned data: a) jsonFlickrApi({"ph ...

What are some strategies for postponing the execution of a basic function for an

Whenever I develop microservices, I often come across situations where one function contains multiple other functions. For instance: functionA(); functionB(); functionC(); return json({status: processed}); All the functions within this block are synchro ...

Runtime Error: Invalid source property detected - Firebase and Next.js collaboration issue

Currently, I am developing a Next.js application that retrieves data from a Firestore database. The database connection has been successfully established, and the data is populating the app. However, I am facing an issue with displaying the image {marketpl ...

appearing like a straightforward process of creating strings in JavaScript

Originally, I thought this task would be easy, but it ended up taking me the entire morning! var insert = '<div class="main_content_half_panel_circle" id="circle_' + c + '"></div><script type="text/javascript">$("#circle_& ...

What is the best way to define a variable in EJS?

I need to populate my database array results on the frontend using EJS. The code snippet I'm using is as follows: var tags = ["<%tags%>"] <% for(var i=0; i<tags.length; i++) { %> <a href='<%= tags[i] %&g ...

Tips for identifying modifications in an input text field and activating the save button

Currently, I am developing a function that can detect any changes made in the text field and then activate the save button accordingly. This code is being executed in Visual Studio 2017, using HTML and JavaScript. (function () { var customer_addres ...

Exploring Alternative Methods for Serving Static HTML Files in an Express Server

Hey there, quick question for you. Let's say I have two static HTML files that I want to serve in Express - 'index.html' and 'contact.html'. I've been playing around with some basic Express code to get them served: const expr ...

Managing code requiring document.title in Next.js with Static Site Generation (SSG)

Currently, I have 2 dynamic SSG pages located under /blog/[slug]. Within these pages, I am rendering a component using next/link. When I click on these links to navigate to another slug, I encounter an issue. The problem arises when I want to execute some ...

Leverage Node.js to access an array from app.js within a module

Within my Node app.js file, I am looking to make my array openConnections accessible by the module sse_server.js for the sseStart function. How can I achieve this without necessarily declaring the array as a global variable in app.js? Here is a snippet of ...

The issue with ng-if not functioning within ng-repeat is that the ng-if directive

My issue is with using ng-if inside an ng-repeat in AngularJS. Despite updating to the latest version on 09/27/2014, I am still unable to make it work properly. The code functions perfectly outside of ng-repeat, and also works fine inside ng-repeat when us ...

Angular JS Tutorial: How to Nest ng-views

When merging two separate Angular apps into one, I encountered the need to nest ng-views. The structure of my sample code (index.html) looks like this: <!doctype html> <html lang="en" ng-app="myApp"> <head> <meta ch ...