Getting props value in parent component using Vue JS

In my development project, I am working with three key components: component-1, component-2, and an App component. Initially, I pass a Boolean prop from component-1 to component-2. Through the use of a @click event, I am able to toggle this prop value between true and false.

App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" width="20%" />
    <component1 />
  </div>
</template>

component-1.vue

<template>
  <div>
    <component2 :have-banner="true" />
  </div>
</template>

<script>
import component2 from "./component-2";
export default {
  components: {
    component2,
  },
};
</script>

component-2.vue

<template>
  <div>
    <button @click="AssignBanner = !AssignBanner">Click me</button>
    <p>{{ AssignBanner }}</p>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    haveBanner: Boolean,
  },
  data() {
    return {
      AssignBanner: this.haveBanner,
    };
  },
};
</script>

I am attempting to access the prop value in component-1 in order to track its changes and develop some additional logic. Unfortunately, I am facing difficulties in tracking this value within component-1.

You can view the code on codesandbox

Answer №1

It seems like you are looking to implement two-way binding for the prop haveBanner. One way to achieve this is by utilizing the .sync modifier if your Vue version is 2.3 or higher.

component-1.vue

<template>
  <div>
    <component2 :have-banner.sync="haveBanner" />
  </div>
</template>

<script>
import component2 from "./component-2";
export default {
  components: {
    component2,
  },
  data() {
    return {
      haveBanner: true,
    }
  },
};
</script>

component-2.vue

<template>
  <div>
    <button @click="assignBanner = !assignBanner">Click me</button>
    <p>{{ assignBanner }}</p>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    haveBanner: Boolean,
  },
  data() {
    return {
      assignBanner: this.haveBanner,
    };
  },
  watch: {
    assignBanner(value) {
      // send updated value to parent component
      this.$emit('update:haveBanner', value)
    },
  },
};
</script>

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

Tapping into the space outside the MUI Modal Component in a React application

Can Modal Component in MUI be used with a chat bot? When the modal is open, can users interact with buttons and inputs outside of it? How can this be implemented? I want to be able to click outside the modal without closing it. Modal open={open} onClo ...

problem encountered when transferring data using ajax

I'm struggling with figuring out how to use an ajax function My goal is to send PHP variables via ajax to another page when a user clicks on a link Javascript function sendData(a, b, c, d) { $.ajax({ url: "page.php", typ ...

Trouble Arising from Making a POST Request to Spotify's API

I am currently developing a web application that allows users to search the Spotify Library, add songs to playlists, and then save those playlists to their Spotify Accounts. Almost everything is functioning correctly except for the saving of playlists thro ...

Error! D3.js is throwing an Uncaught TypeError because it cannot find the function .enter(...).append(...).merge

Currently, I am facing an issue while attempting to construct a table with multiple nested dropdowns using d3.js. The problem arises when switching from a newer version of d3 where my code functions flawlessly to d3.js v3. Upon replacing the newer version ...

"Unlocking the secret to fetching the id of the clicked element within a Highchart context menu

Is it possible to retrieve the id of a clicked button on the highchart context menu? Alternatively, is there a way to execute the click function twice? const contextButtonArray = []; contextButtonArray.push({ { text: 'TEST BUTTON&ap ...

``tips for concealing the sidebar on a Vue.js application`

Welcome everyone, I am a newcomer to Vue and have decided to use a CoreUI admin panel to work on some cool Vue projects. However, I have hit a roadblock while working on the nav.js file. export default { items: [ { ...

Is it possible to retain various delimiters after dividing a String?

In the code below, the someString gets split into an array using specified delimiters in separators var separators = ['\\.', '\\(', '\\)', ':', '\\?', '!&apos ...

"Enhance Your Vue Experience with CKEditor's External Link

I am currently engaged in a Vue project that employs ckeditor within one of its components. My goal is to configure hyperlinks so that they open in a new tab whenever an external link is detected. Based on the documentation, I understand that achieving th ...

Tips for securing a record that is currently being edited by a user in a multi-user application using Laravel and Vuejs

One solution could involve creating a hidden field in the form to hold the fetched_at timestamp, which stores the updated_at timestamp of the current record being updated. Upon form submission, we can compare the fetched_at value with the database's u ...

Leveraging split and map functions within JSX code

const array = ['name', 'contact number'] const Application = () => ( <div style={styles}> Unable to display Add name & contact, encountering issues with splitting the array). </div> ); I'm facing difficul ...

Is there a way to redirect the user directly to the upload page without displaying the response?

Recently, I came across this code snippet that adds a progress bar to an upload form. Currently, the code displays the response from the upload page below the form. However, my goal is to redirect the user to the upload page so they can view the response t ...

Text centered on hover for figure caption

Check out this fiddle http://jsfiddle.net/sLdhsbou/ where I am trying to center the "x" that appears on hover perfectly no matter what size the image is. Also, why does the transition not occur when moving the mouse outside of the figure, unlike when movi ...

What is the best way to utilize regex to replace two elements simultaneously?

I am facing a challenge with manipulating a string of characters by adding span tags to highlight specific words and change their color. While I have successfully implemented the changes for one pattern using regex, I'm struggling to do the same for a ...

Running a React application through a personalized Express server, all the while ensuring seamless automatic updates throughout the development

I currently have a React application along with a completely distinct Express server application. To serve my React app using a customized express server, I utilize the following code within my Express app: app.get("*", (req, res) => { res. ...

Nextjs version 13 encountered hydration failure due to discrepancies between the initial UI and the server-rendered content

I am currently utilizing the latest version 13.1.0. I have implemented a ContextProvider that allows switching between light and dark themes. 'use client'; import { Theme, ThemeContext } from '@store/theme'; import { ReactNode, useState ...

What is the purpose of requiring the explicit invocation of app.listen(port) to enable express-ws to function properly?

I've recently started exploring NodeJS Express and came across the official tutorial from express-ws for setting up websockets in a simple project generated using npx express-generator. While following the tutorial, I noticed that in the app.js file, ...

Dynamic image updates in real-time

Beginning a new project and already facing a roadblock, I could really use some assistance. I have 16 (4x4) images that I am displaying on a page. $max_images = $_GET['images']; $num_images = $max_images; while (($num_images > 0) && ...

Tips on retrieving and showcasing information from various endpoints in React?

I am working with two different endpoints and I need to fetch data from both simultaneously in order to display it in one single element. For example, I want to show data from one table along with the corresponding name from another table if the product id ...

What is the proper way to utilize a variable within the translate3d function?

Currently, I am developing my portfolio and working on a function in JavaScript called translate3d(0,10px,0). My question is, how can I use a variable instead of hardcoding the value 10px? I attempted to use translate3d(0,a,0) where 'a' is a vari ...

The attribute 'use' is not found within the data type 'typeof...', and the property 'extend' is not present within the data type 'typeof'

As I embark on building my very first Vue app using TypeScript, I find myself facing a frustrating issue: Property 'xxx' does not exist on type 'typeof. Despite my efforts to research similar problems, none of the suggested solutions have pr ...