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

Assign a value to the input field based on changes made in another input field

I am brand new to the world of JavaScript and currently grappling with setting a value in an input field based on the onchange event of another input field. Here is my code sample for input field 1: <input type='text' onchange='methodTh ...

delay of Paypal API disbursement for transactions with a range of money values

After browsing through various resources such as this link, that link, and another one on the PayPal developer website, I attempted to implement a payment processing system that allows users to approve a preset amount of money. Similar to services like Ube ...

Dynamic jQuery URL truncater

Is there an on-the-fly URL shortener similar to Tweetdeck available? I have come across several jQuery and JavaScript plugins that can shorten a URL through services like bit.ly when a button is clicked. However, I am looking for one that shortens URLs aut ...

Dealing with Koa-router and handling POST requests

I am facing an issue handling POST requests in my koa-router. Despite using koa-bodyparser, I am unable to receive any data sent through my form. My template engine is Jade. router.js: var jade = require('jade'); var router = require('koa- ...

Managing timestamps of creation and modification with Sequelize and Postgresql

As a newcomer to Sequelize, I find myself grappling with the intricacies of model timestamps management. Despite prior experience with another ORM in a different language, I'm struggling to wrap my head around how to automatically handle "createdAt" a ...

Unable to include Buefy or Bulma in a Vuejs project

I am working on a Vue.js project and I would like to incorporate the Bulma framework and possibly Buefy as well. To start, I used the commands npm install bulma and npm install buefy In the main.js file, my setup looks like this: import Buefy from &apos ...

When I click the back button on my mouse in React, it returns JSON data instead of HTML and CSS

I am working on a web application with two pages: a menu and orders. When I navigate from the orders page to the menu page and click the back button, I receive JSON data instead of the HTML page. The data loads correctly, but the page does not display the ...

The issue of Datatables child row not refreshing when using AJAX

I'm attempting to retrieve child row data in Datatables using AJAX: $('#myTable tbody').on('click', 'td', function () { var tr = $(this).closest('tr'); var row = myTable.row( tr ); if ( row.child.isS ...

Utilizing React JS to neatly display Firebase data in a table

Before I post, I always make sure to do my due diligence by searching on Google, YouTube, forums, or trying to figure it out on my own. I even check questions similar to mine asked by other people, but unfortunately, I'm stuck. Currently, I am using ...

delayed updating of property not visible in angular 10 immediately

I needed to hide a div based on a condition, so I decided to use the hidden property like below: <div [hidden]="isControlDisplayed()?false:true"> The isControlDisplayed() method determines whether to show or hide the div based on the value ...

When Ajax attempts to run a PHP page, it redirects me to a different page

My goal is to create a live chat feature using PHP, MySQL, and AJAX. I have almost got it working perfectly, but I'm stuck on how to submit the chat message without refreshing the page. I have a PHP page called sendchat.php that takes input data and s ...

Why is a div nested inside an overflow: hidden; div not expanding to the full width of its content?

.container { white-space: nowrap; overflow: hidden; } .inner { width: 100%; } .list-item { display: 'inline-block', boxSizing: 'border-box', border: '3px solid black' } import React, { Component } from 're ...

Is there a way I can ensure the values are loaded when the page loads, rather than displaying NaN?

I've recently created a car rental calculator for a client, and it's almost complete. Everything is working smoothly, from the calculations to the conditions. However, I'm facing an issue where the price isn't calculated on page load. I ...

The Vuex store was initialized in main.js, however, it seems to be undefined when accessed in App

index.js: import Vue from "vue"; import Axios from "axios"; import App from "./App.vue"; import router from "./router"; import store from "./store"; const axios = Axios.create({ baseURL: process.env.VUE_APP_BASE_URL }) Vue.prototype.$http = axios; n ...

Activate JavaScript functions by pressing the enter key, allowing for various searches, AJAX requests, and DataTable displays to occur seamlessly without the need to refresh

I recently developed a web page that integrates an AWS API interface to interact with an RDS Aurora MySQL Serverless database. Users can input a SQL statement and click the Query button, which triggers an AJAX request, returns JSON data, and converts the d ...

Troubleshooting Bootstrap 4 Modal in JavaScript and Vue: Uncaught ReferenceError: $ is not defined

I'm struggling to figure out how to trigger a Bootstrap 4 modal from my Vue 3 app using JavaScript. Whenever I try to launch the modal, I keep encountering this error message: $ is not defined at eval When looking for solutions, I noticed that most a ...

When configuring a domain for Express sessions, it prevents the cookie from being stored

I have encountered an issue with my node.js service application and react frontend. I am utilizing Discord OAuth and express sessions for authentication on my application frontend. Everything functions perfectly when running locally, but upon deploying to ...

Utilize the BootstrapVue input component for seamless reusability during changes

I'm a newcomer to VueJs and Bootstrap Vue. Every time I use the input component in my application, which is changed by Bootstrap Vue, I have to update it across the entire application. Would creating my own input component using the Bootstrap Vue co ...

Ways to showcase JSON data with jQuery

My code displays movie data from a JSON variable and populates it on a dropdown list based on the selected city. I aim to include show timings along with other details from the JSON content. The code snippet is as follows: $(document).ready(function() ...

Leveraging Github CI for TypeScript and Jest Testing

My attempts to replicate my local setup into Github CI are not successful. Even simple commands like ls are not working as expected. However, the installation of TypeScript and Jest appears to be successful locally. During the Github CI run, I see a list ...