How can I correctly update values from a sibling component that has been imported in Vue.js 2.0?

My Vue 2.0 project follows the single-file component approach and consists of three components: App (parent), AppHeader, and FormModal. Both AppHeader and FormModal are direct children of App and siblings of each other.

The main objective is to toggle the visibility of the FormModal component when a button in the AppHeader component is clicked. However, I'm struggling to understand Vue's uni-directional data flow. How can I pass an event from the child (AppHeader) back up to the parent (App) to change the form's visibility?

(AppHeader.vue)

<template>
    <header>
        <div class="app-header">
            <h1 class="app-title">Sample Header</h1>
            <a class="link-right" v-on:click="toggleModal()" href="#">
               <i class="fa fa-pencil-square-o"></i>
            </a>
        </div>
    </header>
</template>

<script>
    import FormModal from "./FormModal.vue";
    export default {
        name : "AppHeader",
        props : ['visible'],
        methods : {
            toggleModal () {
                this.visible = !this.visible;
            }
        },
        components : {
            FormModal
        }
    }
</script>

(FormModal.vue)

<template>
    <div class = "form-content" v-if="visible">
        <!-- Some form markup -->
   </div>
</template>

<script>
    export default {
        name : "FormModal",
        props : ['visible']
        //Also have data, methods, and computed here, but they aren't relevant to the example.
    }
</script>

I realize I've misunderstood how to use props in this instance. I need guidance on the correct way to incorporate props when importing a template.

Edit:

Apologies for the oversight. In my project, the App.vue file serves as the parent component for all templates involved.

(App.vue)

<template>
    <div class="app">
        <AppHeader></AppHeader>
        <FormModal></FormModal>
    </div>
</template>

<script>
    import AppHeader from "./AppHeader.vue";
    import Compose from "./FormModal.vue";
    export default {
        data () {
            return {
                views : [AppHeader, FormModal]
            }
        },
        components : {
            AppHeader,
            FormModal
        }
    }
</script>

To recap, App functions as the parent with two sibling components, AppHeader and FormModal. Clicking a button in AppHeader should trigger a toggle in FormModal's visibility. Unfortunately, I haven't fully grasped Vue's uni-directional data flow and could use advice on tackling this scenario.

Answer №1

To integrate the visibility of your app header with a child component (form-modal), you must bind the "visible" data field to the "visible" attribute in the child component. This connection ensures that any changes made to the "visible" data field in the AppHeader will automatically update the form modal as well.

<form-modal :visible="visible"/>
...
<script>
import FormModal from "./FormModal.vue";
export default {
    name : "AppHeader",
    data() { 
      return {
        visible: false
      }
    },
    methods : {
        toggleModal () {
            this.visible = !this.visible;
        }
    },
    components : {
        FormModal
    }
}
</script>

FormModal Template:

<template>
    <div class="form-conten" v-if="visible">
        <!-- Some form markup -->
   </div>
</template>

<script>
  export default {
    name : "FormModal",
    props : ['visible']
  }
</script>

The concept here is that the FormModal component is always listening for changes in the "visible" prop received from its parent, treating it like a "readonly" variable within FormModal.

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

What is the best way to utilize computed properties with nested Vuex objects?

I currently have an object stored in Vuex with the following capabilities: // Defining the object in the state dataObject = {}; // Adding a new key with an empty array state.dataObject[someNumericalId] = []; // Pushing a value into the array state.dataObj ...

Unable to input text using Python Selenium in a textbox

Currently, I am attempting to input text into a specific textarea HTML element using Python Selenium: <div class="spk-c spH-d"><div id="gwt-uid-23" class="sppb-a"> <div class="sppb-b spk-b">For example, flowers or used cars</div> & ...

Resetting the state of toggle/click states in AJAX and jQuery

Currently, I am encountering a small dilemma with a .on function and AJAX in conjunction with a mobile menu. The mobile menu is located in the header of a site that relies heavily on AJAX for its content loading. This poses an issue because when an AJAX ca ...

Problem with implementing swipeable tabs using Material-UI in React

I'm experiencing an issue in my application with the react swipeable tabs from material-ui. I followed all the installation steps recommended in the documentation. Currently, I am encountering the error shown in the screenshot below. Could there be a ...

Using Vue to set an active class on an element and retrieve the current DOM element

I am attempting to apply a class called "active" to the currently selected element without using v-for. When the element is clicked, I assign event.target to the "selected" property. To compare each individual element with the one stored in "selected", I n ...

What are the reasons behind memory leaks and decreased rendering speed when I exit and then reopen a React component (specifically Material-Table)?

I have been working on a basic React example for learning purposes, and I incorporated the use of material-table in one of my components. However, I noticed that each time I change pages and reopen the component (unmount and mount), the rendering speed of ...

Add elements to an array following an AJAX request

On my .cshtml page, I have the following script: $(function () { var tempArray = []; var tbValue = $('#tb1').val(); $.ajax({ url: "/ControllerName/getdata", dataType: 'json', ...

Updating the value of a MongoDB item two days after its creation

I've been working on a NodeJS application that stores form data in a MongoDB database collection. My goal is to implement a function that can modify certain values of the object in the database collection 48 hours after the form data is initially save ...

Filter out specific fields from an object when populating in MongoDB using the aggregate method

Is there a way to use the populate() function in MongoDB to exclude specific fields like email and address, and only retrieve the name? For example: const results = await Seller.aggregate(aggregatePipeline).exec(); const sellers = await Seller.populate(re ...

How can I showcase images stored in an array using JavaScript?

I am currently developing a role-playing game (RPG). In order to enhance the gameplay experience, I am trying to implement a for loop that will dynamically generate buttons on the screen. Here is the code snippet I have created so far: $(document).ready(f ...

Vue: Issue with reusability when calling a component with varying arguments numerous times

I am facing an issue where I need to render the same component multiple times with different parameters. I have two objects, and based on the type provided, I want to display either a text input or a numeric input. When I try to call the component twice wi ...

Unable to disable webpack HMR

I have set up my project using express version 4.14.0, webpack version 1.14.0 with babel and its presets. I obtained this sample webpack configuration from a reliable source: var path = require('path'); module.exports = { entry: './main. ...

Expand the <div> by clicking on it, then hover away to return it to its normal size

One interesting feature I have on my website is a <div> that expands when clicked, and returns to normal size with another click. However, I am looking for something a bit different... What I want is for the <div> (with the class name .topHead ...

Analyzing conditional statements in React with State management

I've been encountering challenges with if statements correctly evaluating, displaying either true all the time or exhibiting unexpected behavior when passing variables or using state variables for evaluation. I realize this might be related to differe ...

I have received a JSON multi-line string after entering information in a textarea

I've been working on a small social network project where users can create and share posts. However, I encountered an issue with formatting when storing and displaying the posts. When a user enters text with line breaks in the post creation form, it ...

Retrieving the data from a GET request to use in a subsequent request

I'm currently utilizing Vue to interact with an external API on a Drupal website. In order to make this interaction dynamic for each Drupal user, I need to fetch a token from Drupal first. My approach involves making two GET requests. The initial requ ...

Is it possible to retrieve 2 arguments within a function in a non-sequential manner?

Let's say there is a function with arguments A, B, C, D, and E. Function(A, B, C, D, E) However, not all arguments are needed all the time. For instance, only A and C are needed in some cases. Currently, I would have to call the function like this: Fu ...

Vue.js - When Property is Undefined and How to Render it in Browser

My experience with Vue has been quite puzzling. I've encountered an issue while trying to render a nested property of an object called descrizione, and although it does work, I keep receiving a warning from Vue in the console: TypeError: Cannot rea ...

What could be the reason for the undefined initial state in my vuex store?

I am facing an issue with vuex-typescript where the initial state is always undefined. However, it works fine when I reset the state and refresh the window. Below is my setup for a simple module: import Vue from "vue"; import Vuex from "vuex"; import { m ...

Ways to verify if a Discord.js snowflake is present in a collection of other identification numbers

I'm currently developing a Discord.js bot and I want to create a system where only specific IDs listed in a JSON file can trigger certain commands. However, I'm unsure about how to implement this logic within an if statement. if (message.author. ...