Switch the state of a variable using the emit function

I need to change the value of the 'visualizacao' variable to true when a button in another component is clicked.

COMPONENT 1 containing the visualizacao variable

<template>

        <div>
            <card-patrimonial v-if="!visualizacao"/>
            <visualizacao-patrimonial v-else/>

        </div>

    </template> 

    <script>
        import Patrimonial from '@/modules/Casos/Patrimonial/_components/Patrimonial.vue';
        import VisualizacaoPatrimonial from '@/modules/Casos/Patrimonial/_components/VisualizacaoPatrimonial.vue';

        export default {
            name: "CasosPartes",
            components: {
                'card-patrimonial': Patrimonial,
                'visualizacao-patrimonial': VisualizacaoPatrimonial,
            },
            data(){
                return{
                    visualizacao: false
                }
            }
        }
    </script>

COMPONENT 2 with the button to toggle the visualizacao variable of component 1

<template>

    <button>Toggle Component</button>

</template>

<script>

    export default {

        data() {
            return {

            }
        }
    }
</script>

Is there a way to achieve this using emit?

Answer №1

Inside Component2:

<template>
  <button @click="changeComponent()">Switch component</button
</template>

<script>
    export default {

        data() {
            return {

            }
        },
        methods: {
            changeComponent(){
                this.$emit("listenButtonEvent");
            }
        }
    }
</script>

Inside Component 1:

<template>
    <div>
        <patrimonial-card @changeComponent="changeView" v-if="!view"/> <visual-patrimonial v-else/ >
    </div>
</template> 

<script>
    import Patrimonial from '@/modules/Casos/Patrimonial/_components/Patrimonial.vue';
    import VisualizacaoPatrimonial from '@/modules/Casos/Patrimonial/_components/VisualizacaoPatrimonial.vue';

    export default {
        name: "CaseParts",
        components: {
            'patrimonial-card': Patrimonial,
            'visual-patrimonial': VisualizacaoPatrimonial,
        },
        data(){
            return{
                view: false
            }
        },
        methods: {
            changeView(){
                this.view = true;
            }
        }
    }
</script>

Answer №2

Check out this example: https://jsfiddle.net/z2v3nsuq/

const ButtonClicker = {
  template: `<button @click="$emit('clicked')">Click me</button>`,
};


new Vue({
  el: '#app',
  components: { ButtonClicker },
  data() {
    return {
      clickCount: 0,
    };
  },
});

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

Revising the $.parseJSON Function in jQuery 1.9.1 to Match jQuery 1.8.3's Implementation

With the latest version of jQuery, 1.9.0, there have been changes in the implementation of $.parseJSON which is causing some issues for us. We relied on how earlier versions of jQuery handled null and empty strings, where it would return a null value inste ...

Encountering a getMacChromiumEdgeDriverArchitecture error while using wdio/selenium-standalone-service

As I continue to learn WebDriverIO and adjust to MacOS, I encountered an error while trying to execute a spec file using "npm run test:wdio". The error message is as follows: > [email protected] test:wdio /Users/vinicius.correia/Desktop/dev/automat ...

Error encountered in NodeJS: Promise TypeError - res.json is not a function while handling pre-signed URLs. This results in

I'm having trouble generating a list of pre-signed URLs for files in my private S3 bucket. Despite researching similar issues on multiple forums, I can't seem to resolve the error with the res.json function in my code. Can someone please help me ...

Is there a method `Object.values()` available in TypeScript?

How can I iterate through all values of an Object in TypeScript that I want to use for filtering another array? I have searched on Google and came across Object.values(), but it seems like it doesn't work in TypeScript. Is there an equivalent method ...

Hidden form in JavaScript does not submit upon clicking the text

My previous question was similar to this but with a smaller example. However, the issue with that code differs from my current code. (If you're curious, here's my previous question: JavaScript Text not submitting form) Currently working on my fi ...

Incorporating a series of image links into a Three.js project with the addition of a

My latest project involves creating a reflection cube with randomly changing images on each side every time the site is reloaded. Here is the code I have written: var imgAr = [ 'sources/instagram2/image1.jpg', 'sources/instagram2/image2.jp ...

Display a message box in the external window just before the close event

I am trying to implement a message box that will appear when the user clicks the (X) button of an Ext window. However, I am facing an issue where the window closes before the message box is shown. Below is the code snippet I have written: var assignReport ...

Record of Recaptcha actions is not showing up in the reports

My method of running the recaptcha script is as follows: let data = { action: 'homepage' }; grecaptcha.ready(() => { grecaptcha.execute('RECAPTCHASITEKEY', data).then((token) => { recaptcha_token = token; }); ...

The Javascript query is returning an [object Object] data type

I am facing an issue with a JavaScript file that is querying a SharePoint list. Specifically, the Priority drop down in the query result is displaying as [object OBJECT]. I suspect it has something to do with the var query string where I have added the &ap ...

Can components be designed in a way that includes elements such as buttons or text areas in the code, but allows for them to be excluded when the component is used?

I have a custom form component that I designed. Depending on certain cases, I want the form to display either a button or a text field instead of the input field as currently coded. function FormTypeOne(props) { return ( <form className={classes.f ...

performing a GET request directly from a <script> element in the index.html file

I am currently developing an application that utilizes Angular.js on the client side and Node Express on the server side. On my server side, I am using a staticAsset module. Within my index.html file, I have a lengthy list of JavaScript files that need t ...

Update the image with a new one using jQuery and PHP, then refresh the page to see

I'm currently utilizing simpleImage, a PHP image manipulation library. My aim is to externally rotate an image using AJAX and replaceWith functions. It successfully replaces the image, but unfortunately it doesn't refresh after rotation. Here&ap ...

Connecting elements within an object using VueJs

Within my object "info_login," I gather account information: async created() { try { const res = await axios.get(inscriptionURL); this.comptes = res.data; this.comptes.forEach(element => { const data = {'pseudo': ...

Adding routes dynamically in nodeJS using Express is a powerful way to manage your server

Is there a way to dynamically add paths to nodeJS within a running program? Instead of relying on kludged solutions like resetting the server when files change, I am looking for a more efficient method. Any suggestions? EDIT: This project is focused on pr ...

The strict-origin-when-cross-origin policy is enforced when submitting a POST request through a form to a specific route

Currently, I am diving into the world of Node.js, express, and MongoDB by reading Greg Lims's book. However, I've hit a roadblock when trying to utilize a form to submit data to a route that should then output the body.title of the form in the co ...

Developing a synchronous loop in Node.js using the web-kit module

My goal with my app using node.js and webkit is to scan each proxy listed in a file.txt and determine if the proxy is working. However, I am encountering an issue where my loop does not wait for the "http.get" test on line 11 to complete before moving on ...

Is utilizing a standardized logging system considered a best practice for a node and express application?

I am currently working on a node.js application that consists of several dozen modules and uses bunyan for logging with JSON output and multiple configurable streams. I have been searching for good examples on how to implement a logger instance across all ...

What is the best way to retrieve the ID of the input element using a jQuery object?

After submitting a form with checkboxes, I retrieve the jQuery object containing the checked input elements. var $form = $(e.currentTarget); var $inputs = $form.find("input.form-check-input:checked") Here is an example of how the inputs are stru ...

The YouTube-Search NPM module is producing unexpected outcomes

I recently integrated the youtube-search NPM library with express to fetch the first youtube video based on a song name. app.get("/search", (req, res) => { var search = require("youtube-search"); var SONG = req.query.SONG; var opts = { maxR ...

Tips for writing unit tests for components using vitest in the latest version of Nuxt

I've been working on transitioning from Vue 3 to Nuxt 3. I've successfully written unit tests for my components using vitest in my Vue app, however, when running the same tests in the Nuxt app, I encounter the following error: Error: Failed to ...