A guide on seamlessly connecting props with local data using 2-way binding in Vue 3

Seeking guidance on binding a component's prop to its own data property. Let's say we have a component named ModalComponent

<template>  // ModalComponent.vue
   <div v-if="showModal">
      ...
      <button @click="showModal = !showModal">close the modal internally</button>
   </div>
</template>

<script>
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      showModal: false,
    }
  }
}
</script>

<style>
</style>

Let's imagine that this modal is used as a reusable component within a parent component, and an external button triggers its display.

<template>
  <button @click="showChild = !showChild">click to open modal</button>
  <ModalComponent :show="showChild" />
</template>

<script>
export default {
  components: {ModalComponent},
  data() {
    return {
      showChild: false,    
    }
  }
}
</script>

<style>
</style>

How can I ensure that clicking the parent button opens the modal by binding the local showModal to the show prop? And once the modal is closed using the internal close button, how do I make it pop up again when the parent button is clicked? (This scenario involves Vue 3)

Any assistance would be greatly valued. Thank you.

Answer №1

Instead of passing a prop, the best approach for this scenario is to utilize v-model:

In the child component, declare modelValue as a prop and emit its value to the parent using the $emit function:

<template>  // ModalComponent.vue
   <div v-if="modelValue">
      ...
      <button @click="$emit('update:modelValue',!modelValue)">close the modal internally</button>
   </div>
</template>

<script>
export default {
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
  },
  emits: ['update:modelValue'],

}
</script>

In the parent component, simply use v-model to bind the value:

<template>
  <button @click="showChild = !showChild">click to open modal</button>
  <ModalComponent v-model="showChild" />
</template>

<script>
export default {
  components: {ModalComponent},
  data() {
    return {
      showChild: false,    
    }
  }
}
</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

Styling Javascript Objects

[ [ {"path":"path2","value":"kkk"}, {"path":"path0","value":"uuu"}, {"path":"path1","value":"ppp"} ] ] The result obtained from my manipulation is shown above. However, I require the format to be as depicted below: ["path":"pat ...

After the rendering of the HTML, the value of the jQuery input does not change

Here we have a function that loads HTML onto the form class in a file. The quest[q] locates the appropriate HTML template to load from an array of templates. The HTML being loaded contains an input with an id of "p". I am attempting to set the value of th ...

Mastering the use of useMasterKey in Parse with Node.js: A guide

Greetings everyone, I have developed my app using parse.com but now I need to utilize the master key as some users have administrative roles. Initially, I attempted to use the JS SDK but was advised to switch to Cloud Code. So, I tried using Express and ...

Changing the key name for each element in an array using ng-repeat: a guide

In my current project, I have an array of objects that I am displaying in a table using the ng-repeat directive. <table> <thead> <tr> <th ng-repeat="col in columnHeaders">{{col}}</th> //['Name&apo ...

Accessing PHP variables within a React componentTo access external

How can I pass the id selected in a menu from a react component to a PHP file, after already knowing how to send data from PHP to the react component? $.ajax({url: '/file.php', type: 'POST', dataType: 'json', ...

Discover the steps to update the information displayed on a tab through $stateProvider

I'm working on a view that has the following structure: <h2>Data Package Management</h2> <div class="row push-down-md"> <tabs data="tabData" type="tabs"></tabs> <div class="col-md-12"> <tabset&g ...

Is it feasible to invert the order of arguments in async.apply?

According to the async documentation: apply(function, arguments..) Creates a function continuation with certain arguments already applied. This can be useful when combined with other control flow functions. Any additional arguments passed to the returned ...

React Native displaying identical path

Is there a way to dynamically change routes in React Native when a button is pressed? Inside my SplashContainer component, I have the following method: handleToSignUp = () => { console.log("Running handleToSignUp") this.props.navigator.push({ ...

What is the process for importing a file with an .mts extension in a CJS-first project?

Here's a snippet from a fetchin.mts file: import type { RequestInfo, RequestInit, Response } from "node-fetch"; const importDynamic = new Function("modulePath", "return import(modulePath);") export async function fetch(u ...

Tips for utilizing a Map instance in JSX?

Is there a more efficient method for iterating over a Map object in JSX? const map = new Map<string, string[]>([ '2023-08-23': ['string1', 'string2'], '2023-08-24': ['string3', 'string4' ...

Troubleshooting cross-origin resource sharing problem with Express NodeJS server running on localhost

Utilizing the fetch web API to send a POST request from ReactJS to an Express NodeJS server running on localhost with different ports. Using Client Fetch API fetch("http://localhost:8081/test", { method: "post", mode:"no-cors", headers: { ...

Verification - enter a unique key for each ajax call

As I develop a new app, I am aiming to separate the HTML/JS layer from the PHP layer in order to prepare for a potential phonegap version in the future. One major concern I have is regarding authentication. Since I won't be able to rely on session va ...

Witness the profound impact unfolding at a deeper level

I need to track changes in an array and log when a value inside it has been updated. Currently, my code only logs items when they are added or removed from the array. I would like to also log when a specific property like item.Circle.position changes. I h ...

Troubleshooting Block-scoped errors on Heroku using Node.js and Express

Currently, I am working with node.js and express on the Heroku platform. While working on the route file, I encountered an issue when using the let keyword. The error message displayed was: SyntaxError: Block-scoped declarations (let, const, function, cla ...

Adding information into material-ui dropdown using React JS

I could use some assistance with populating data into a Dropdown using material-ui in React. I am new to React and unsure about how to achieve this. I know that I can pass props to the dropdown, but it's not very clear to me. Here is my current code: ...

What is the significance of the colon found within a VueJS/Vuetify/HTML component tag?

Incorporating Vuetify into my project has led me to this VueJS, Vuetify, or HTML inquiry. The component in question displays as follows: <v-list-tile v-for="item in menuItem.items" :key="item.type" :style="`background: ${item.colour}`" :h ...

Challenges with resizing windows in jQuery

I'm currently working on optimizing my jQuery code and everything seems to be running smoothly so far: jQuery $(document).ready(function(){ $(".fadeinbg").click(function(){ $("#content").fadeIn(); }); var height = $(window).height() ...

Interacting with jQuery UI Droppable by setting acceptance criteria before submitting a form

My goal is to create a draggable item that can be dropped onto a specific zone. The challenge I'm facing is in displaying a form for inputting information and storing it in a database. If the input is successfully stored, the drop action will be succe ...

Navigate to the location using AngularJS elements in the JavaScript iframe1

Dealing with an issue while working on AngularJS. I am facing a frustrating problem where I am attempting to use one link to open links in two separate iframes. All aspects of this function correctly, except for the actual links. The issue arises when usin ...

Issue with UseState causing a re-render not to be triggered

My orders list state works perfectly on the initial update. However, when an order in the database gets updated, the order list is updated but fails to trigger a re-render even with <...> const [orders, setOrders] = useState([]); useEffect(( ...