How to achieve two-way binding using @Prop() in Vue Cli 3 with TypeScript?

Here is the source code snippet:

This is the Child Component:

<template>
  <v-snackbar
    v-model="showSnackbar"
    :bottom="y === 'bottom'"
    :left="x === 'left'"
    :multi-line="mode === 'multi-line'"
    :right="x === 'right'"
    :timeout="timeout"
    :top="y === 'top'"
    :vertical="mode === 'vertical'"
  >
    {{ text }}
    <v-btn
      color="pink"
      flat
      @click="showSnackbar = false"
    >
      Close
    </v-btn>
  </v-snackbar>
</template>

export default class AliUMSSnackbar extends Vue {
  @Prop() private showSnackbar!: Boolean;
}

This is the Parent component:

<ali-snackbar v-bind:showSnackbar="showSnackbar"></ali-snackbar>

However, when the Close button is clicked, an error occurs: '[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "showSnackbar"'

Answer №1

For users of Vue 2.3.0+, leveraging the .sync modifier allows for a convenient "two-way binding" for a prop.

To achieve this, emit events using the format update:myPropName.

In the child component, updating the prop on button click is done like so:

<v-btn color="pink" flat @click="() => this.$emit('update:showSnackbar', false)">Close</v-btn>

Furthermore, adjust the parent component as shown below to listen to the emitted event and update a local data property titled showSnackbar.

<ali-snackbar v-bind:showSnackbar.sync="showSnackbar"></ali-snackbar>

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

Uploading files in Angular 5 with additional properties of other objects

I am facing a challenge with uploading a file as part of a property to an object within a form. Most documentations I have come across only focus on services that handle standalone files. In my case, I have a form with various text inputs and date pickers, ...

Utilizing Vuetify in Typescript: Making Use of Data() Properties

ie data() { return { bar: false rules: { foo: (value) => { if (this.bar) {} } } } } The code is functioning correctly. What steps can be taken to help typescript comprehend this? If this is considered a " ...

Utilizing a Buefy element without Vue.js integration

Is there a way to generate a Buefy notification without utilizing a Vue component? Specifically, I'm attempting to implement a Buefy notification within the axios interceptor below: import axios from "axios"; import { Notification } from "buefy/dist/ ...

Leverage generic types and allow acceptance of objects with arbitrary keys

Is it possible to allow the Use function argument type to accept any unknown key, as well as correctly type the keys from SomeGeneric? function Example (opt: { valid?: boolean }) { } type SomeGeneric = Parameters<typeof Example>[0] function Use(op ...

Is there a way to transform a complex nested class object into a simple object without losing its methods

Is there a way to convert a deeply nested class object into a plain Object type while still retaining methods like getters and setters? class A { id = ""; data = { sync: {} }; } class SyncService { syncResultServiceA = { ...

Problems with looping through arrays in Vue

One of the challenges I'm facing involves a large table that is fetched from an API in the form of a scores array. This array contains player data which needs to be looped through to display each player. <tr class="RT&quo ...

Prevent UI from updating while backend calls are being made in Vuejs

Imagine a scenario where a user in my application can make multiple backend calls before the first one is even finished. How can I ensure that the User Interface freezes after each call until the backend operation completes in Vuejs? Any suggestions woul ...

When attempting to log a console statement using Vue Axios, an unexpected error occurs and returns an unexpected

My attempt to display jsonplaceholder posts using axios and vue is resulting in an unexpected console output that points back to the console.log statement. Check out the code snippet below: <script> import axios from 'axios'; export d ...

Querying subdocuments within an array using MongoDB's aggregation framework

Currently, I'm facing a challenge while developing a statistics dashboard for a meditation app. I'm struggling with creating a MongoDB query to fetch the most popular meditations based on user progress. The key collections involved are users and ...

Using scrollIntoView() in combination with Angular Material's Mat-Menu-Item does not produce the desired result

I am facing an issue with angular material and scrollIntoView({ behavior: 'smooth', block: 'start' }). My goal is to click on a mat-menu-item, which is inside an item in a mat-table, and scroll to a specific HTML tag This is my target ...

A guide on serving a Spring Boot web application with Vue front end and H2 database using Cloud Foundry

After following a tutorial that utilized Vue as the front end and Spring Boot as the backend, I successfully set up the front end by placing the built files from Vue's dist folder into Spring Boot web's src\main\resources\static di ...

What are some solutions for troubleshooting setInterval issues?

I have a h1 element with a v-for loop that displays items from my array in the following format: <h1 v-for="(record, index) of filteredRecords" :key="index" :record="record" :class="get ...

What are the steps to implement $navigateTo() in a NativeScript Vue application?

What could be causing $navigateTo(Page) to not work? Visit this link for more information ...

"Error message: Trying to import a component in Angular, but encountering a message stating that the component has no exported

When creating a component named headerComponent and importing it into app.component.ts, an error is encountered stating that 'website/src/app/header/app.headerComponent' has no exported member 'headerComponent'. The code for app.headerC ...

The preflight request for Firebase Storage CORS did not pass the access control check due to not having an HTTP status of ok

When attempting to upload an image to Firebase Storage, I encountered an error in the Chrome console: Access to XMLHttpRequest at 'https://firebasestorage.googleapis.com/v0/b/%22website-admin-c9ce6.appspot.com%22VITE_APP_VERSION%3D0.0.0/o/MYx2YMuRBw ...

Resetting the v-model value can be done after hiding an input element using conditional rendering

I currently have a setup with two inputs: the first being a switch and the second a text field that is conditionally displayed when the switch is set to true. In the scenario where a user sets the switch to true, enters something in the text box, but then ...

Troubleshooting: Inability of Angular2 Component to access class property within template

Here is the code snippet that I am currently working with: post.component.ts: import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { JobsService } from '../jobs.service'; @Component({ ...

Want to enhance user experience? Simply click on the chart in MUI X charts BarChart to retrieve data effortlessly!

I'm working with a data graph and looking for a way to retrieve the value of a specific column whenever I click on it, and then display that value on the console screen. Check out my Data Graph here I am using MUI X charts BarChart for this project. ...

What is the reason for the array length view not updating when a new object is added?

I am dealing with an array of objects and the length is displayed using this code snippet: <strong *ngIf="cart">{{ cart.length }}</strong> Even though when I add items to the array, both the array and its length are showing correctly ...

Error in VS2015 when attempting to assign a two-dimensional array in TypeScript build

I've run into some build errors in my TypeScript project in Visual Studio 2015. Despite the application working fine in the browser, I'm unable to publish it due to these errors. export var AddedFields: Array<Array<Field>[]>[]; myGl ...