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

Exploring VueJS: How to effectively showcase numerous nested properties within objects

I'm working on a multi-level navigation component in VueJS. While I can successfully retrieve and display the first two levels, I'm struggling to access and display the nested property called name of the children array within my for loop. How can ...

Top method for troubleshooting JavaScript code in Visual Studio 2010

Is there a way to troubleshoot JavaScript code in Visual Studio 2010 for MVC Razor projects? ...

Steps on how to trigger an onmouseover event for entire blocks of text:

I'm currently in search of an onmouseover code that seems to be elusive on the vast internet. A CSS box format has been successfully created: .box { float: left; width: 740px; height: 300px; margin-left: 10px; margin-top: 10px; padding: 5px; border: ...

React: The error message "p is not defined" is showing up in the component file due to the no-undef

In my React application, I am looking to display a list of menu items from an array and show the detailed description of each item upon clicking. The array of menu items is stored in a separate file called dishes.js. The menu items are rendered using a Me ...

Synchronous async routes in Node Express

My express server requires fetching data from multiple external sources for each request, with the logic separated into various routers (some of which are not under my control). These routers operate independently, eliminating the need for one to wait on ...

Guide to implementing CSS3 transitions with prefixes using JavaScript

Is there a way to apply CSS styles using JavaScript when I don't have access to the CSS file? #fade div { -webkit-transition: opacity 1s; -moz-transition: opacity 1s; -o-transition: opacity 1s; -ms-transition: opacity 1s; transition: ...

analyzing strings by comparing their characters to another string

In a scenario where I have two strings; let's call them string a="a-b-c" and string b="a-b". I am looking to determine whether every letter in string b is present within string a. ...

Using async/await in a for loop | The await keyword can only be used inside an asynchronous function

I've been attempting to execute the following code: async function verifyExistingUsers(db, users) { return new Promise((resolve, reject) => { var companies = [] for (const [index, user] of users.entries()) { let comp ...

Received TypeError: Unable to call reset function - issue clearing input field post ajax request

Having Trouble Clearing Input Fields After AJAX Request: $.ajax({ type: "POST", url: "river_flow.php", data: { username: $("#username").val(), idv:$("#idv").val(), comment: $("#comment").val()}, cache: false, success: function(da ...

"Bootstrap-Wizard: How to troubleshoot the onPrevious function not working when used with an

I have been incorporating a bootstrap wizard into one of my applications, and I have encountered an issue. When attempting to utilize the index position of the tabs to achieve a specific goal, I found that it only works with the next button and not with th ...

What purpose does sending null to XMLHttpRequest.send serve?

Have you ever wondered why send is often called like this? xhr.send(null) instead of just xhr.send() ? W3, MDN, and MSDN all mention that the argument is optional. Additionally, the ActiveX control seems to work without it: hr=pIXMLHTTPRequest.Create ...

Is it possible to implement formvalidation.io in a React project that is using Materialize-css?

Can the formvalidation.io plugin be used with React and Materialize-css in a project? My project consists of multiple input components that may or may not be within a form. I want to utilize formvalidation for input validation. However, I am unable to find ...

Bringing custom JavaScript functions into a Vue.js component

In my Vue.js project, I have an abundance of Javascript processing that is all local and doesn't require server-side functionality. I'm exploring the possibility of importing a file containing specific processing functions (such as mathematical a ...

What are the steps to create a unique popup div effect with jQuery?

Upon clicking the icon on this page, a mysterious div appears with information. I'm completely baffled by how they achieved this cool effect using css/jQuery tools. Can anyone shed some light on the mechanism behind this? ...

Can the MemoryRouter be successfully nested within the BrowserRouter in a React application?

I've been on a quest for some time now, trying to uncover whether it's feasible to utilize MemoryRouter solely for specific routes while maintaining the use of BrowserRouter in general. My goal is to navigate to a particular component without alt ...

Converting a timestamp from PHP in JSON format to date and time using JavaScript

Within the JSON file, there is a timestamp associated with each user login. An example of this timestamp is: timestamp: "1541404800" What steps should be taken to convert this timestamp into date and time format? ...

The conditional statement does not align with my Regular Expression

I'm experiencing a peculiar issue with my regular expression matching in the code snippet provided. Even though the alert confirms a match between the strings, the if statement fails to trigger. Any insights on why this might be happening? Appreciate ...

After placing two divs within another div and applying justify content, an unexpected blank space has appeared

I am currently working on a website project using the Next.js framework for React and Tailwind CSS for styling. However, I have come across an issue that is causing some trouble. My goal is to position an image on the right side of the page while keeping t ...

Provide net.socket as a parameter

What is the best way to pass the net.socket class as an argument in this scenario? Here's my code snippet: this.server = net.createServer(this.onAccept.bind(this)); this.server.listen(this.port); } Server.prototype.onAccept = function () { // Ho ...

Preventing Columns in SlickGrid from Being Reordered

Is there a way to prevent specific columns in SlickGrid from being reordered? I have tried looking for a solution but couldn't find one. Unlike the 'resizable' option, there doesn't seem to be an option for each column to allow or disal ...