VueJs - I'm struggling to figure out the best way to send a Boolean value to a child component

I am aware that this topic has been covered before, but I am struggling to grasp how I can pass a variable to a child component.

My goal is to pass the 'displayTogglingMenu' from the parent component to the 'toggle' function in the child component.

Parent component

  data(){
    return  {
      selectedItem: 1,
      displayTogglingMenu: false,
      items: [
        { text: 'Home', name: 'home', icon: 'mdi-home' },
        { text: 'Courses', name: 'courses_index', icon: 'mdi-school'  },
        { text: 'Enrolments', name: 'enrolments_index', icon: 'mdi-format-list-bulleted' },
        { text: 'Lecturers', name: 'lecturers_index', icon: 'mdi-account-tie' },
      ],
    }
  },   

Child Component

data(){
    return  {
        toggle: valueOfParentComponent,
        alertMessage: '',
        loadTable: true,
        courses: [],
        expendable: [],
        ...
},   

The following is the component I am seeking to conceal, as requested by Tim:

<div class="table-container">
    <b class="circle"></b>

    <v-app>
        <v-content>
            <v-card>
                <v-card-title>

                    <v-text-field
                        v-model="search"
                        append-icon="mdi-magnify"
                        label="Search"
                        single-line
                        hide-details
                        class="search"
                    ></v-text-field>

                    <v-spacer></v-spacer>

                    <router-link :to="{ name: 'new_course'}" class="newItem">New course</router-link>

                </v-card-title>

                <v-data-table
                    :headers="courseHeaders"
                    :items="courses"
                    :items-per-page="10" 
                    :loading="loadTable"
                    loading-text="Loading... Please wait"
                    :search="search"
                    :single-expand="singleExpand"
                    :expanded.sync="expanded"
                    item-key="id"
                    show-expand
                    class="elevation-1"
                >

                    <template v-slot:item.title="{ item }">
                        <transition-group name="list" tag="p">
                            <span class=" list-item" v-bind:key="item">{{item.title}}</span>
                        </transition-group>
                    </template>

                    <template v-slot:item.actions="{ item }">
                        <transition-group name="list" tag="p">
                            <span class=" list-item" v-bind:key="item">
                                <router-link :to="{ name: 'edit_course', params: { id: item.id } }" class="edit-btn" title="Edit">
                                    <v-icon med>mdi-pencil</v-icon>
                                </router-link>
                                <v-btn v-on:click="deleteCourse(item.id)" class="del-btn " title="Delete" >
                                    <v-icon med>mdi-delete</v-icon>
                                </v-btn>
                            </span>
                        </transition-group>
                    </template>

                    <template v-slot:expanded-item="{ headers, item }" >
                        <td :colspan="headers.length" class="item-description" >
                            <h4 >Course description:</h4> 
                            <p >{{ item.description }}</p>
                        </td>
                    </template>
                    
                </v-data-table>

            </v-card>
        </v-content>
    </v-app>

    <b class="circle2"></b>
</div>

Answer №1

Primary Component

<template>
  <Component :toggle="displayTogglingMenu" />
</template>

<script lang='ts'>
import Component from 'Componenet.vue'
import { defineComponent } from 'vue';
export default defineComponent({
    components: {Component},
    data() {
        return {
            displayTogglingMenu: false
        }
    }
});
</script>

Secondary Component

<template>
  <div v-show="toggle"></div>
</template>

<script lang='ts'>
import { defineComponent } from 'vue';
export default defineComponent({
    props: ['toggle']

});
</script>

The boolean value of displayTogglingMenu in the primary component will be passed as a prop named toggle in the secondary component

You may access the prop using this.$props.toggle depending on the scenario

Answer №2

If you want to pass data from a parent component to a child component, you can easily do so using properties. Check out the documentation for more details.

For example:

<child-componenet :prop-name="parent value that can also be reactive"></child-component>

Properties in Vue are reactive, meaning your child-component will respond to any changes made to its properties. You can then use these properties in conditional statements like v-if or v-show.

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

Add a text to the values in a column of a table when the IDs are the same

I am working on a project that involves updating a table based on a data change. The table has a column for ID and when the ID matches a specific variable, I need to append the word 'Updated!' next to it in the table cell. However, the code I hav ...

Error in AJAX call while attempting to decrypt plain text using Crypto-JS

I recently integrated Crypto-JS plain text encryption/decryption into my NodeJS application. Testing the code on the server-side showed that everything worked perfectly: var encrypted_string = CryptoJS.AES.encrypt(input_string, '123Key'); var ...

What is the best way to initially hide a div using slide toggle and then reveal it upon clicking?

Is there a way to initially hide the div tag and then animate it in a slide toggle effect? I attempted using display:none on my '.accordion_box' followed by show() in slideToggle, but this results in adding the CSS property display: block. My goa ...

What sets apart isSuccess from onSuccess in react-query?

When the useMutaion is successful, I would like to implement some logic. However, I am not sure whether to use the boolean 'isSuccess' or the callback function 'onSuccess'. Can you advise on the best approach? const { mutate: creat ...

Firefox does not accept cookies sent with XHR CORS requests

I am currently in the process of creating a login page on the domain "example.com" that makes an Ajax request to the domain "other_domain.com." If the credentials are valid, this request will return a session cookie. My goal is to then redirect to the "oth ...

Message indicating NoteContext is not defined

In my React project, I first created a NoteContext and then initialized an array using the useState hook. This array was imported into the Notes component where I used .map to display the titles of the objects in the array. However, when running the code, ...

The TypeError thrown by Mongo .updateMany() indicates that the property 'updateMany' of the object is not a valid function

Currently, I have a collection named users, which contains the following documents: Document 1: { "_id": { "$oid": "5934fd84d6ba4c241259bed1" }, "first_name": "Joe", "last_name": "Smith", "username": "jsmith", "email": "&l ...

Using the 'gf' command in Vim to resolve JavaScript modules with a Webpack tilde alias

Recently, I joined a Vue.js project that makes use of the tilde (~) notation in module imports. For example: import WhateverApi from '~/api/whatever'; The project repository is a mix of various files including a Vagrant machine setup, a Laravel ...

Send user a notification upon detecting changes in the database - using JavaScript and AJAX!

Hey there! I'm diving into the world of JavaScript and AJAX for the first time, and I could really use some guidance on a particular issue. I'm looking to implement a feature where the user is notified whenever there is a change in a value of a ...

What is the best way to incorporate several functions within a resize function?

Is it possible to incorporate multiple functions within the windows.width resize function? I have been experimenting with some code, but I would like to restrict its usage to tablet and mobile devices only, excluding laptops and PCs. Any suggestions on h ...

Guide on updating a variable to the following string within an array

Snippet: months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October&apos ...

Merge web address when form is sent

I'm currently working on a search application using the Django framework and the Yelp API as my backend, which is functioning properly. However, I am facing some challenges with the frontend development, specifically integrating Leaflet.js. My search ...

Guide on submitting a pre-filled form with data pulled from an array of objects using vue

My current school project involves creating a web app for dog walkers. I am currently working on a form to update the information of dogs owned by a user. This data is stored in an array of objects, where each object represents a dog's information. I ...

How can I target the first checkbox within a table row using jQuery?

I am seeking a way to determine if the first checkbox in a table row is selected, rather than checking all checkboxes within that particular row. Currently, I am using this code: var b = false; $j('#tb1 td input:checkbox').each(function(){ ...

The attempt to perform the 'removeChild' function on the 'Node' resulted in an error related to sliding out

I am encountering an error in the chrome console related to a slide-out function. The error points to the line document.body.removeChild(document.getElementById("overlay04")); in my JavaScript function. How can I prevent this error from occurring? Thank yo ...

Sending blank data using ExpressJS ajax feature

I am encountering an issue while trying to send JSON data to my server as the POST requests are coming through with empty bodies. Below is the TypeScript code I am using on the front end: function sendData() : void { console.log("Sending data..."); var na ...

Having Trouble with Your React.js Rendering?

I'm starting to learn React.js but I'm having trouble rendering it into the HTML. I can't figure out what's wrong. Any help would be greatly appreciated. Below are the HTML and JSX code: (Note: Full links to the react library are incl ...

The watch functionality is failing to work within a specialized attribute directive that is being utilized within a separate custom element directive

I'm currently working with two directives that handle separate functionalities. I am attempting to utilize the attribute directive within an element directive, but I'm encountering issues with the watch function not working on the attribute direc ...

Do you need assistance with downloading files and disconnecting from clients?

When looking at the code snippet below: async function (req, res, next) { const fd = await fs.open("myfile.txt") fs.createReadStream(null, { fd, autoClose: false }) .on('error', next) .on('end', () => fs.close(fd)) . ...

Updating array of documents in MongoDB with a new array of documents

Is there a way to properly update an array of objects in a collection without having to remove and re-insert them? I am worried about losing data if the insert operation fails after removing the existing array. How can I efficiently update all documents in ...