Suggestions for changing sub-component data in Vue

I have a scenario where I am using a component with tabs inside. The Head component (parent) includes the following code:

<v-btn @click="setSelectedTab('Set') "> ... 
<component :is="selectedTab"></component>

Within the Set component (child component), I have some emits that will modify the data.

 <div>
    <head-set
      v-show="showHeadSet"
      @settings="
        showHeadSet = false;
        showScreenSettings = true;
      "
      @robotix="
        showHeadSet = false;
        showRobotix = true;
      "
    >
    </head-set>
    <Robotix v-show="showRobotix"></Robotix>
    <screen-settings v-show="showScreenSettings"></screen-settings>
  </div>

<script>
data() {
    return {
      showHeadSet: true,
      showRobotix: false,
      showScreenSettings: false,
    };
  },
</script>

When the button is clicked (

@click="setSelectedTab('Set') "
), my goal is to reset the data in the Set component back to its initial state (
showHeadSet: true,showRobotix: false,showScreenSettings: false,
).

Do you have any suggestions on how to achieve this?

Answer №1

To effectively pass data to child components in your scenario, utilizing properties is the most straightforward approach.

Here's how your parent component would appear:

<template>
  <div>
    <v-btn @click="setSelectedTab('Set') "> ... </v-btn>
    <component :is="selectedTab" :settings="yourSettings"></component>
  </div>
</template>

<script>
export default {
  data: () => ({
    yourSettings: {
      showHeadSet: true,
      showRobotix: false,
      showScreenSettings: false
    }
  }),

  methods: {
    setSelectedTab() {
      // your code
      this.yourSettings = {
        showHeadSet: true,
        showRobotix: false,
        showScreenSettings: false
      };
    }
  }
}
</script>

In the child components, make sure to define the props like so:

<script>
export default {
  props: {
    settings: {
      type: Object,
      required: true
    }
  }
}
</script>

You can utilize the props as computed or data variables and modify the settings based on your requirements. When using the setSelectedTab method in the parent component, you can simply revert the data back to its default state.

For more information regarding props, refer to the documentation.

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

How can I combine an ordinary image and a CSS2D image in THREE.js CSS2DRenderer and save them together as a single .jpg file?

After implementing the following code... (1) I successfully saved regular rendered THREE.js scenes as .jpg files; (2) Additionally, I managed to utilize CSS2DRenderer to display CSS2D labels on top of the canvas; (3) Now, my goal is to save the image wi ...

Methods for delivering static resources on multiple routes in Express JS

Is there a way to effectively serve static resources for all routes in Express JS? I attempted to serve files with static resources using the following code snippet: app.use(Express.static(`${this.PATH}`)); app.use(Cors()); app.use(Express.json()); app.g ...

The error message in Express points to module.js line 550 and states that the module cannot be

I am currently in the process of setting up a basic express application using the code below: const express = require('express'); const app = express() const bodyParser = require('body-parser'); const cookieParser = require('cooki ...

Exploring Vue.js3: Simplifying Nested Array Filtering

Currently, I am in the process of sifting through an Array that contains nested arrays. To handle this task, I utilized computed and crafted a function called filteredEgg(). However, I seem to be overlooking something, as I'm only returning the main ...

Error: excessive recursion detected in <div ng-view="" class="ng-scope">

I've recently started learning angularJS and I've encountered an error that I need help with. Below is my index.html file: <body ng-app="myApp"> <div ng-view></div> <a href="table">click</a> <script ...

In JavaScript, alert a message once all images have been clicked

I'm encountering a small issue with my javascript code. I am developing a game for a school project where the objective is to click (remove) fish using a fishing rod. However, the game does not have an end condition set up, so players cannot win. Belo ...

I need help figuring out how to navigate between different pages in my Vue-cli app that has multiple pages configured

After following the guide on https://cli.vuejs.org/config/#pages, I successfully configured vue-cli3 to build a multiple page application. My project consists of 2 static pages, and I set up the vue.config.js file as shown below. However, when running the ...

Implement pagination for API calls within a React Component

I am trying to implement pagination for the results of an API call. The following code snippet shows how I am making the API call using Axios: apiCall() { const API = `http://www.omdbapi.com/`; axios.get(API, { params: { apikey: proces ...

Using Vue.js along with vuex and axios allows for data retrieval only upon the second load

After creating a Vue.js app with vuex as a central store and using axios for basic API calls, I implemented the following store action: loadConstituencyByAreaCodeAndParliament({commit}, {parliament_id, area_code}) { axios.get('/cc-api/area-code/ ...

JavaScript validation controls do not function properly when enabled on the client side

Following the requirements, I have disabled all validation controls on the page during the PageLoad event on the server side. When the submit button is clicked, I want to activate the validations and check if the page is valid for submission. If not, then ...

Recursion using Node.js Promises

I'm facing some difficulties while iterating through my Promises and completing my parser code: let startFrom = 0, totalRecords = 10000, doneRecords = 0 const rows = 10 const parserRequests = function () { if (startFrom <= totalRecords) { ...

Calculate the combined sum and alter the values of three input fields

There are three text boxes (testbox, testbox2, testbox3) that receive values from an input field, radio button selection, and checkbox. The correct values are displayed in testbox, testbox2, testbox3. Additionally, the sum of testbox, testbox2, testbox3 n ...

Transform the styles from a React component into Cascading Style Sheets

I have been tasked with transitioning all the styles from the JavaScript file to the CSS file while ensuring the design remains intact. I am facing an issue where using the CSS styles breaks the search field design. The original design can be seen here: S ...

The echo statement is failing to show any value following the ajax request

I am in need of assistance. I would like to output the value from a PHP echo statement using an AJAX call. Currently, the code is functioning without any errors. When I select options from a dropdown menu, the value is displayed on the console by using con ...

Implementing jQuery selector for CSS and properly handling special characters in the code

I've been attempting to use jQuery to change the background color of a radio button. I provided the CSS code below, but even after escaping special characters in jQuery as shown below, the solution still isn't working. #opt5 > [type="radio"]: ...

Handling a change event for a mat-datepicker in Angular 7 can be tricky, especially when its value is tied to an optional input parameter. Let's dive into how to

I've recently started working with angular development and encountered a challenge with a mat-datepicker. The value of the datepicker is connected to filterDate using [(ngModel)] as an @Input() parameter. I have implemented a handleChange event that e ...

Having trouble retrieving the URL from JSON data - every time I attempt to access it, it just shows as undefined. Any suggestions

Having trouble extracting the URL from JSON, as it shows undefined. Any suggestions? <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta> <script language="JavaScript" type="text/javascript" ...

The npm package installation process encountered difficulties in accessing the Chart.Js library

Currently, I am in the process of developing a web application that tracks and logs hours spent on various skills or activities. The data is then presented to the user through a bar graph created using Chart.js. Initially, I was able to display a mock grap ...

Link the values of mongoose array to a distinct identifier

This question may come across as vague, but I'll do my best to explain it clearly. Just a heads up, I'm relatively new to working with mongoose :) So, I have this mongoose schema where different values are stored for each user: let userSchema = ...

JavaScript: Converting an array of strings into an array of objects with proper formatting

After scanning barcodes, I have an array of strings that currently contains the following data: var array = ['NEW', '1111', 'serial1', 'serial2, 'NEW', '2222', 'serial3', 'serial4'] ...