Invoking a method in Vue.js from another component

I'm just starting out with VUE and I have a unique challenge for my project. I want to have a button on one page that triggers a function on another page. I know some may ask why not keep the button and function on the same page, but I am exploring how to call functions from different pages as part of learning. I hope to make it clearer by asking this question.

Whenever I try to call the method function from chairPage.vue in homePage.vue, I get an error saying world is not defined in homePage.vue. Can someone please help me understand why this error occurs and suggest the best way to resolve it?

I have two Vue components: homePage.vue and chair.Vue. The goal is to have a button on homePage.vue trigger the method function on chairPage.vue.

Home Page

<template>
   <div id="homepage">
     <b-button variant="info" @click="buttonClicked()">Click</b-button>

     <chairComponent ref="world"/>

   </div>
</template>

<script>
  import chairComponent from '@/components/chair.vue';

  export default {
  props: [],
  
  methods:{
    buttonClicked(){
      this.$refs.world.hello();
    }
  }

  }
</script>

Chair Page

<template>
   <div id="chairComponent">
      <p v-if="displayText == '1'"> HELLO WORLD </p>
   </div>
</template>

<script>
  export default {
    props: ['world'],
    data(){
      return{
        displayText:'',
      }
    },
    methods:{
      hello(){
        console.log('inside child component hello function');
        this.displayText = '1';
      }
    }
  }
</script>

Answer №1

If you want to pass props to a child component and watch for changes on those props to trigger a function, you can do so with Vue.js:

Vue.component('Chair', {
  template: `
    <div id="chairComponent">
      <p v-if="displayText == '1'"> HELLO WORLD </p>
   </div>
  `,
  props: ['world'],
  data(){
   return{
    displayText:'',
   }
  },
  methods:{
    hello(){
      console.log('inside child component hello function');
      this.displayText = '1';
   }
  },
  watch: {
    world() {
      if (this.world) this.hello()
    }
  }
})

new Vue({
  el: '#demo',
  data() {
    return {
      val: null
    }
  },
  methods:{
    buttonClicked(){
      this.val = true
      setTimeout(() => {this.val = false},0)
    }
  }
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>
<div id="demo">
 <div id="homepage">
   <b-button variant="info" @click="buttonClicked">Click</b-button>
   <chair :world="val" />
 </div>
</div>

Answer №2

Everything is working flawlessly in the code snippet below

Vue.component('Chair', {
  template: `
    <div id="chairComponent">
   </div>
  `,
  data(){
   return{
    displayText:'',
   }
  },
  methods:{
    hello(){
      console.log('inside child component hello function');
   }
  },
})

new Vue({
  el: '#demo',
  methods:{
    buttonClicked(){
      this.$refs.world.hello();
    }
  }
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>
<div id="demo">
 <div id="homepage">
   <b-button variant="info" @click="buttonClicked">Click</b-button>
   <chair ref="world" />
 </div>
</div>

It seems like including the components section in the homepage.vue file could potentially solve any issues

<template>
   <div id="homepage">
     <b-button variant="info" @click="buttonClicked()">Click</b-button>

     <chairComponent ref="world"/>

   </div>
</template>

<script>
  import chairComponent from '@/components/chair.vue';

  export default {
  props: [],
  // New changes added below 
  components: {
    chairComponent
  },
  methods:{
    buttonClicked(){
      this.$refs.world.hello();
    }
  }
  }
</script>

Answer №3

You have the ability to trigger an event from a child component to its parent by using $emit in Vue.js. Learn more here!

Example in Child Component:

hello() {
  ...//your code here
  this.$emit('customEvent', someValue)
}

Example in Parent Component:

<template>
  <child 
    @cutomEvent="function"
  />
</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

Updating the variables of HTML components using JavaScript after making an AJAX request

I am using ajax to fetch a list of user data. But after this ajax call, I need to display the data in an HTML structure like a datasheet for each user. My question is how can I store the HTML code in a functional and elegant way to maintain readability and ...

Creating a process to produce a random number and send it directly to an automated email

I'm currently utilizing a form builder from jqueryform.com to construct a registration form. My goal is to have each registered user assigned with a unique account number, which will be a randomly generated 6-digit number. Additionally, I want the pro ...

Using ES6 Classes to map an array of variables

If I have a list of 5 people's names, such as Sam, Ash, Moe, Billy, Kenzi, and want each name to have properties like doneHomework and lazy using a class: class Person { constructor() { this.doneHomeWork = 0; this.lazy = false; ...

Only perform the Rails ajax call once initially

I'm currently working on creating a drop down menu that contains a substantial amount of content, and I would like to use an ajax get call to load everything upon mouse enter. Here is my code written in coffeescript: class @SecondaryMenu construct ...

Exploring the intricacies of parsing nested JSON data

Could someone assist me with understanding the following json data? { "Message":"The request is invalid.", "ModelState":{ "model.ConfirmPassword":["The password and confirmation password do not match.","The password and confirmation passwo ...

Encountering ReferenceError when attempting to declare a variable in TypeScript from an external file because it is not defined

Below is the typescript file in question: module someModule { declare var servicePort: string; export class someClass{ constructor(){ servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined' } I also attempted t ...

Having trouble retrieving textfield value with jQuery

On my website, I have an invoice.jsp page that requires jQuery to calculate values in textboxes. Within the invoice, there is a quantity textbox. When a user enters a quantity, the price should be dynamically calculated as (total_subPrice= unit_price * qu ...

Utilizing Google Maps to generate outcomes for an online platform

My approach with Google Maps is a bit unconventional. Instead of rendering images, I aim to execute JavaScript code that processes data and returns a text response. However, I soon realized that running JavaScript as a remote web service might not be pos ...

Detecting unutilized space in a collection of divs with varying sizes using JavaScript and CSS

To better understand my issue, I created a StackBlitz demo: https://stackblitz.com/edit/angular-aqmahw?file=src/app/tiles-example.css Screenshot My tiles can have four different widths (25%, 50%, 75%, 100%). The tiles must fit on only two lines, so if a ...

Printing array of API results in NodeJS using ExpressJS

I have been working with the Twitter API to retrieve tweets and store them in an array. I am looking to print the entire array on my HTML document for display purposes. Excited to see it work! Thanks! Check out the code snippet below: var express = requi ...

Leveraging data generated by a CasperJS script within an AngularJS application

After using yeoman.io to create an angular.js single page application, I found myself with app.js managing routes, mycontroller.js scripts, and an index.html file filled with "bower_components" references for libraries installed through the command line us ...

extract values from a JavaScript function on a website

Currently, I am facing a challenge in automatically retrieving elements from a webpage and I seem to be stuck on a few things. My approach involves looping through all classes named 'trList' using document.getElementsByClassName('trList&apo ...

Utilize an external stylesheet for your Vue web component to avoid inline styles

For my web component, I am utilizing the vue-cli-service to handle the building process. All styles associated with this component are consistently inlined within the javascript file. To create the web component: vue-cli-service build --target wc --name co ...

Xap or js Silverlight media player

Currently developing a Silverlight video player, I stumbled upon the JW Player for inspiration. I know that Silverlight apps are typically contained within .xap files, but JW Player utilizes JavaScript scripts to implement Silverlight logic. Can you plea ...

Leveraging the power of Ajax and Javascript to handle and process conditional if/else statements

Hey there, I'm new around here so I hope I got this right. Currently, I'm diving into the Ajax for Dummies book after enjoying the PHP one years ago. However, I've hit a roadblock with my first real Ajax program. It took me ages to locate th ...

Looking for a specific phrase in the data entered by the user

I am dealing with data in ckeditor that looks like this: <p>test 1</p> <p>test 2</p> <p><img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICw ...

Troubleshooting jQuery Sortable Issue with Table and Row Width in ASP.NET MVC View

I am facing an issue with jQuery UI sortable while trying to make my table grid sortable. Despite not getting any error messages, the sortable function is not working as expected. I have never utilized this method in a MVC (views/razor) project before. An ...

Tips for running Scrapy and Selenium on a webpage that utilizes angular JavaScript to serve data

I have been working on a web scraper that follows this process: Visit site A -> click on the buy now button -> redirected to Amazon -> scrape data -> return to site A The issue I am facing is that the site is built using AngularJS, and I am h ...

Having trouble finishing the npm installation process

Having trouble with completing 'npm install'. Can someone please assist me?</p> <pre><code>Encountering a warning about an old lockfile while running npm install. The package-lock.json file was created with an outdated version o ...

What is the best way to make an input text the focus when an item on a dropdown menu is clicked?

I have a website with a dropdown menu and an input box. I want the user experience to be more seamless by automatically focusing the mouse cursor inside the input box when they click on an option in the dropdown menu. This way, users can start typing right ...