What is the process of invoking a function from a different component in Vue 3?

I attempted to use the $on method and

this.$root.$refs.compname_component = this;
, but encountered some errors. Please see my code below:

formComponent.vue

<template>
  <div v-if="showForm">
    create Form
  </div>
</template>
<script>

export default {
  props:[],
  setup(props) {
    return props;
  },
  data() {
    return {
      formData:{},
      showForm:false
    }
  },
  created() {
    // this.$root.$refs.tableCommon = this;
    // this.$root.$refs.compname_component = this;

  },
  mounted() {
    console.log('form mounted');
    // this.$root.$on("displayForm", () => {
    //   this.displayForm();
    // });

  },
  methods: {
    displayForm:function(){
      this.showForm = true;
    }
  },
}
</script>

commonComponent.vue

<template>
    <div class="col-10 text-end custom-inline-spacing mb-3">
      <button type="button" class="btn btn-outline-secondary" @click="showCreateForm">Create</button>
    </div>

</template>
<script>
export default {
  props: [],
  setup() {
    return {}
  },
  data() {
    return {
      
    }
  },
  mounted() {
    console.log('mounted common')
  },
  methods: {
    showCreateForm : function(){
      // this.$refs.form.displayForm();
      // this.$root.$refs.compname_component.displayForm();
      // this.$root.$emit("displayForm");
      this.createForm.displayForm();
    }
  }
}
</script>

app.js

require('./bootstrap')


import { createApp } from 'vue'
import tableCommon from './components/CommonComponent'
import createForm from './components/formComponent';

const app = createApp({})

app.component('vue-common', tableCommon);
app.component('create-form', createForm);

app.mount('#app')

What I actually want is to call formComponent.displayForm() from CommonComponent.

Answer №1

To conditionally show a child component, consider moving the logic from the child component to the parent component.

ParentComponent.vue

<template>
    <ChildComponent v-if="showChild" />
</template>

Alternatively, you can pass a prop to the ChildComponent to selectively display specific parts of it.

ParentComponent.vue

<template>
    <ChildComponent v-bind:show-child="showChild" />
</template>

ChildComponent.vue

<template>
    <div v-if="showChild">
        ...
    </div>
    <div>
        ...
    </div>
</template>

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

Using Three.js to import and cast rays on a .obj model created in Blender

I have successfully imported a 3D terrain using Blender and the OBJLoader in Three.js. In addition, I have created a mesh (highlighted in yellow in the image below) that I want to follow the mouse cursor while it hovers over the terrain. I have attempted t ...

How can we nest a div within the outermost parent element?

Consider a scenario where there are 3 different divs named grandParent, Parent, and Child. Although the parent's tag is placed inside the grandParent, due to the use of position: absolute; property, the parent ends up being displayed outside the grand ...

Display dates using a 24-hour format with Vue and v-calendar

Having trouble configuring my v-calendar datetime picker to display in 24h format. I have been reviewing the documentation but haven't been successful so far: <v-date-picker is-expanded id="match-date-time" v-model="date" mode ...

Storing prop object in LocalStorage when clicking on a Vue3 component

I am currently attempting to pass a prop (faction) from a Component called Faction Option when the @click event for the option occurs. FactionOption.vue <script setup> import { selectFaction } from '../../composables/selectFaction'; def ...

Enhance your Nuxt.js website with a dual layout design option for each page

As a newcomer to Nuxt.js, I am currently in the process of transitioning a Vue project to Nuxt.js. My goal is to implement two different layouts on a single page: the default layout and a secondary one called the settings bar. In the settings page, I hav ...

Mastering the art of completing a form using AJAX

I'm working on a checkbox that triggers AJAX to create a new log. It populates the necessary information and automatically clicks the "create" button. However, I'm facing an issue where the hour value is not changing. Any help on what I might be ...

Configuring git npm dependencies to aid in debugging purposes

This is my first time trying to debug a library in my application and I'm not entirely sure how to go about it. I initially installed the library with npm install @react-pdf/renderer, but debugging was proving difficult. Then, I found a useful answer ...

The TypeScript error occurs when attempting to assign a type of 'Promise<void | Object>' to a type of 'Promise<Object>' within a Promise.then() function

I'm currently working on a service to cache documents in base64 format. The idea is to first check sessionStorage for the document, and if it's not there, fetch it from IRequestService and then store it in sessionStorage. However, I've encou ...

AngularJS to validate image dimensions (width and height) on upload

Hello, I am new to working with Angular JS. I have been experimenting with a login form that includes a file upload field for the user picture. The input field code looks like this: <input type="file" file-model="userPic"/> When I submit the form i ...

How can you sustain a backend connection using NodeJS as users navigate through different pages?

Currently, I am establishing connections through thrift (node-thrift) with a backend server for api calls. The communication is bidirectional (push/pull) to NodeJS. As users navigate various URLs and Node serves jade templates and javascript files using C ...

Struggling to Create a Survey with Included Message: Error - Unable to Initialize MessageEmbed

I'm attempting to create a poll feature for my discord bot that displays both the poll question and results as an embedded message. While I've managed to get the poll information in plain text format, I'm encountering an error when trying to ...

Learn how to read the contents of a v-textarea line by line with the help of JavaScript in V

In my v-textarea component, I have set the following properties: <v-textarea v-model="pmidInput" name="input-PMID" ...

How can I extract just the initial 2 letters of a country name using AmCharts maps?

Having trouble with Amcharts maps. I have a map that displays countries as United States, but I only want them to show as US. Is there a country formatter available for this issue? Any help is appreciated. ...

When running the test, the message "Unable to resolve all parameters for BackendService" is displayed

Upon executing the ng test command, the following error was displayed. This is my service specification: describe('BackendService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [ { p ...

Updating multiple records in MongoDB using ObjectID as the criteria for selection can be achieved by leveraging the

I am currently working in the Mongo shell on Ubuntu and have a Collection with 1 million documents. My goal is to select 50,000 records based on their ObjectID and update one of the values. Is there a way to specify a range of 50,000 documents for the upd ...

Is there a way to execute PHP scripts using JQuery or AJAX without causing the page to refresh?

REFRESHED CODE I'm attempting to execute PHP scripts within my main PHP file where all content will be presented. My goal is to exhibit the outcomes from my PHP script including the SQL queries in use. I also aim to implement the feature of showcasin ...

Touch Screen Button Interaction

Planning to create a Kiosk website with HTML5 that includes point and drag & drop functionality. The site will have buttons and images for user interaction, with actions triggered by finger touches on the screen instead of mouse clicks. Would it be more ...

Exploring the search feature within Redux and React-Native

The search functionality in redux is giving me some trouble. I have written the following code for it, but strangely enough, it's not working properly. Interestingly, the same code works perfectly when used without redux. searchItems: (name ) => ...

`Can I embed inline .svg images into a Nuxt application?`

Is there a way to dynamically include an SVG HTML in a Vue Nuxt application and be able to style it? I tried creating a component but instead of the image, I am getting text data:image/svg+xhtml.... Any suggestions on how to resolve this issue? <templ ...

"Implementing a comment system using Node.js and MySQL: A comprehensive guide

Hey there! I have some data that I want to use to create a hierarchical data example. { id_commentForum: 1, id_user: 1, id_thread: 1, comment: 'This is the First Comment', parent: 0, created_at: Wed Jun 22 2016 13:36:38 G ...