0

I'm new to vuejs and I'm trying to build a simple single file component for testing purpose.

This component simply displays a bool and a button that change the bool value. It also listen for a "customEvent" that also changes the bool 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 works fine. when I click on it the value changes. but when I receive my event, the 'event received' is displayed in the console but my bool doesn't change.

Is there a way to access the components data from my code?

Thanks and regards, Eric

2 Answers 2

1

You can move ipcRenderer.on(...) into vuejs's lifecycle hooks like created.
See: https://v2.vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! moved it to beforeMount() {...} worked like a charm!
@Eric Very glad it helped you :D
1

You are setting up the event listener outside of the component's options which you export by using

export default{ //... options }

Set up the event listener inside the vue options so the vue instance has control over it, in your case modifying dara property

As choasia suggested move the event listener to `created() life cycle 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> 

Now you component will starting listening for that particular even when the component is created

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.