How can we pass a function to a child component in Vue 2.0?

I am facing a challenge with passing a function link to the child component in Vue. Although it is functioning correctly, the code appears in HTML format. How can I enhance this?

In my Vue instance, I have:

app = new Vue({
    ... some code
    data: {
      onAppClose: null,
      onAppSend: null
    }
})

I would like to add any function from the global window or register one within the Vue instance.

app.onSend = () => console.log('data')

Subsequently, I need to pass this function to the child component:

<div id="app">
        <dynamsoft-component v-if="displayComponent" 
            :docs="docs"
            :onAppSend="onSend"
            :onAppClose="onClose"
        ></dynamsoft-component>
    </div>

However, when checking the HTML template in the console, it shows:

<div id="app">
 <div onappsend="()=>{}" onappclose="function (data) {
    console.warn('dwdawad')
    console.log('data')
}"></div>
</div>

Answer №1

The example code you provided doesn't seem to make much sense - are you trying to add a listener instead of a div or pass a function to a child component?

I believe it's the latter scenario. Vue offers custom events for that purpose.

In the parent template, you can use:

<div v-on:appsend="someMethod" v-on:appclose="someOtherMethod"></div>

And in the parent component methods:

methods: {
  someOtherMethod: function (data) {
    console.warn('dwdawad')
    console.log('data')
  },
  // ...
}

To emit from the child component:

this.$emit('appclose', {id: 'whatever'} /*pass data here*/)

Edit:

I'm still unsure how those functions would be directly included in the template, but one issue is that HTML is not case-sensitive. So, using kebab-case like :on-app-send is necessary, even if written as :onAppSend, Vue will convert it appropriately in the component.

Answer №2

Vue.js is a new tool for me, but after checking out the tutorial on their website, it seems to be pretty straightforward.

The Vue style guide provides useful recommendations regarding props naming conventions. You can find more information at this link.

Vue.component('dynamsoft-component', {
  props: ['onAppSend'],
  template: '<button v-on:click="buttonclick">click me</button>',
  methods: {
    buttonclick(e){
      // Check if onAppSend is defined.
      if(Boolean(this.onAppSend)){
        this.onAppSend();
      }
    }
  }
})

new Vue({
  el: '#app',
  methods: {
    onSend: function(){
      console.log('child clicked');
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
  <dynamsoft-component :on-app-send="onSend"></dynamsoft-component>
</div>

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

Discover the secrets of extracting the ID from a MenuItem within a Menu

Table Ui with menu Struggling with fetching the correct user ID in the edit button The edit button for all users is only displaying the last user's ID If the edit button is not nested inside the Menu, it works fine. However, within the Menu, it onl ...

"Implementing a button in a flask data table: A step-by-step guide

Hello, I am facing an issue with adding a button to a Bootstrap datatable in Flask (Python) using JavaScript. Any tips or solutions would be greatly appreciated. I am trying to achieve something like this: I have attempted to return the button with JSON d ...

Tag editor assessing the input's width for SO

I've been working on a tag editor similar to Stack Overflow's and it's coming along nicely. The only issue I'm facing is calculating the width of the textbox after a tag has been selected by the user. For each tag added, I try to adjus ...

I'm struggling to grasp the reason behind the error message stating that x is not a function

Can someone help explain why I keep getting the error message "5Style is not a function"? NationalLevelCategoriesChosenList = [ ["5Style", "5MelodyHarmony", "5RhythmTempo", "5TextureStructureForm", "5Timbre"] ], [ [] ]; if (NationalLevelCategoriesC ...

Transferring information between pages in PHP

Currently, I am exploring the most effective way to pass data between two pages (Page A to Page B) using PHP for a specific scenario: Page A: This page displays a gallery of images with titles. The PHP file makes a database call to an images table, which ...

Maintaining microsecond accuracy when transferring datetime values between Django and JavaScript

It appears that django, or the sqlite database, is saving datetimes with microsecond precision. However, when it comes to transferring a time to javascript, the Date object only works with milliseconds: var stringFromDjango = "2015-08-01 01:24:58.520124+1 ...

Problem with translating a variable into a selector in JQuery

When attempting to make my Jquery code more flexible, I decided to extract the selector and access it through a variable. However, despite creating variables for both selectors, neither of them seem to be functioning properly. I am confident that the issue ...

Tips for creating a unique exception in AngularJS?

I have a customException.js script with the following service: app.service('CustomException', function() { this.CustomException1 = function (message) { if (!message) { message = "Custom Exception 1 occurred!"; } return { ...

Encountered SyntaxError: An unexpected token has been found while integrating leaflet with flask

Despite adding all necessary scripts and configuring my API_KEY in config.js, I keep getting an error message saying "Uncaught SyntaxError: Unexpected token." I have double-checked my API key multiple times, and it seems to be correct. Here is a snippet f ...

When using TypeScript with custom components as children in React, the `type` returned by React.Children is a string representing the function

It might sound a bit odd, or maybe I'm completely off track here. While going through some articles and React documentation on getting children and identifying specific child components using React.Component.map(), I ran into an issue with my custom c ...

Enhancing infinite scroll functionality with ajax integration

After implementing a method to enable infinite scroll on my website using the following function: window.onscroll = yHandler; function yHandler(){ var wrap = document.getElementById('wrap'); var contentHeight = wrap.offsetHeight; var yOffset = w ...

The clash between Kendo UI and jQuery UI

I implemented Kendo UI for the date picker, and I'm looking to incorporate jQuery UI for the autocomplete feature. Upon adding the jQuery auto complete to my code, I encountered the following error: Uncaught TypeError: Cannot read property 'e ...

Is it possible to use require() to read a .json file from a dependent library?

Is it possible to access a .json file within one of my dependent libraries? I'm hesitant to use fs to read ./node_modules/somelib/properties.json because the library could have been installed globally. Is there a way to achieve this using require in ...

Issues with Vercel's JavaScript Environment Variables Accessibility

I am encountering an issue trying to access environment variables on Vercel using JavaScript (TypeScript). Despite setting them under /settings/environment-variables, I receive undefined when attempting to access them with process.env.TURSO_DATABASE_URL du ...

Managing OAuth2 redirections on the frontend: Best practices

I am currently working on implementing an OAuth2 flow for a Single Page Webapp, but I am facing challenges in dealing with Frontend/JavaScript redirects. Regarding the backend setup, I have it all sorted out: utilizing a library that takes care of everyth ...

How can I implement Google Analytics Event tracking for all <audio> tags using Javascript?

I am looking to implement a Google Analytics Event for all audio tags on my website. Currently, I have a script that targets audio tags with a specific class: <script> /* a test script */ $(function() { // Execute function when any element with t ...

JSON response is not being successfully passed in PHP Ajax form validation

I've been struggling to solve my code for the past few days but haven't had any success. I'm attempting to validate my login form using AJAX, however, it seems like there's an issue with my Jquery AJAX script. Every time I try, the con ...

Place content following a three.js display created within a <div id="mainWindow">

Recently, I created a small Three.js animation and embedded it in my HTML page like this: <div id="mainWindow" class="popup_block"> <!-- JavaScript for simulation --> <script src="../temp/webgl-debug.js"></script> <scri ...

Utilizing PNG images with color in CSS, HTML, or JavaScript

On my website, I have an image in PNG format. I am wondering if there is a way to change the color of the image using HTML5, JavaScript, or CSS. Ideally, I would like the image to be changed to white by inverting its colors (changing black to white, not al ...

Node and Angular Error: The specified file or directory does not exist

I have been using the tutorial from scotch.io to build my first node and angular application. I encountered a common issue with relative paths online resulting in the error message Error: ENOENT: no such file or directory. However, after following the tuto ...