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

Tips to stop scrolling when clicking on a link in a Vue.js carousel

How can I prevent the page from scrolling when clicking on a link in a Vue.js carousel? I've created a carousel card to mimic the ones found on Netflix's main page. It works fine on a single component but when I add multiple carousel components ...

Return a string to the client from an express post route

I'm attempting to return a dynamically generated string back to the client from an Express post route. Within the backend, I've set up a post route: router.post('/', async (req, res) => { try { // Here, I perform computations on ...

Issue with importing React: 'Module not found: Unable to locate'

I've organized my React project with a folder system, as shown in the screenshot below: https://i.stack.imgur.com/Rl9Td.png Currently, I'm attempting to import from context.js, located in src/context.js, into index.js, found in src/components/K ...

I'm encountering an unfamiliar error within my Discord.js bot, and I'm unsure of both its cause and the appropriate solution. Additionally, I'm unsure which specific file

I'm facing a recurring issue with my bot terminal. It's been causing me trouble for the past four days, functioning intermittently without any pattern. I'm struggling to track down the specific file where this error is originating from. Any ...

What is the best way to use appendChild within an AJAX get function to manipulate the DOM

I've been working on a code function where I try to append a list item (li) into the HTML received in 'msg', but it's not functioning properly. Any ideas why? function handleFileSelect(evt) { var files = evt.target.files; $(&ap ...

How can you retrieve a value in NodeJS Promise (Q) even when the promise fails?

As I dive into the world of promises in my NodeJS projects, I encountered a challenging situation. Despite reading the Promises/A+ spec and conducting extensive searches online, I struggled to find an elegant solution for accessing a value generated within ...

Generating HTML widgets dynamically with jQuery: A step-by-step guide

Looking for a way to display an interactive widget on your page while allowing users to generate multiple instances and interact with them simultaneously? Imagine having a widget like this: <div id="my_widget"> <script type="text/javascript" ...

A simple method for bulk editing in Angular UI Grid

Is there a way to enable mass editing in Angular UI Grid by allowing all rows to show editable input fields at once, rather than just one at a time? I have searched online for a solution without success and am now turning to this forum for help. If anyone ...

What is the best way to pass values between JSP Expression Language and Javascript?

I have a request object with the following content: List<Integer> list What is the best way to loop through this list using JavaScript? I am interested in obtaining the values of each element within the list. Note that these list values are not cu ...

Guide to setting up a custom js file in Laravel admin template

Currently working with Laravel 5.8 and utilizing the laravel-admin Template for administrative purposes. There are times when I require custom JavaScript and CSS files specifically for certain admin controllers. How can I include these JS and CSS in lara ...

The object filtering process is experiencing issues due to the presence of a null value in the column

I am trying to extract object data based on a specific value from an array. While the code snippet below works well when there are no null values, it fails to work properly when encountering null values in the column. For reference, you can check out this ...

Use Javascript to toggle the display to none for a specific table row (tr)

Is there a way to implement JavaScript code that will hide a specific table row using display:none;, and then reveal it again when a button is clicked? ...

Steps to connect two drop-down menus and establish a starting value for both

In the scope, I have a map called $scope.graphEventsAndFields. Each object inside this map is structured like so: {'event_name': ['field1', 'field2', ...]} (where the key represents an event name and the value is an array of f ...

JavaScript Age confirmation Overlay

I designed an age verification popup with the help of some online tutorials and a friend due to my limited knowledge of JavaScript. Check it out live here- My issue is that I want this popup to load/appear after the page content loads, but I'm not s ...

Creating Comet applications without the need for IFrames

Currently embarking on my journey to develop an AJAX application with server side push. My choice of tools includes Grizzly Comet on Glassfish V2. While exploring sample applications, I've noticed that most utilize IFrames for content updates on the c ...

`Developing reusable TypeScript code for both Node.js and Vue.js`

I'm struggling to figure out the solution for my current setup. Here are the details: Node.js 16.1.x Vue.js 3.x TypeScript 4.2.4 This is how my directory structure looks: Root (Node.js server) shared MySharedFile.ts ui (Vue.js code) MySharedFi ...

Tips for transferring form data from a React frontend to the backend Node.js server

I have been attempting to send FormData from React JS to my backend (Express Node server) with the code snippet provided below. However, I am encountering an issue where req.body.myFormData in expressTest.js is showing up as empty. Despite trying various ...

Transferring information from offspring to parent

Greetings! I'm currently getting my feet wet with React and finding myself stuck on an issue regarding passing states. Is it possible for me to pass a child state to a parent component in order to selectively render other child components? ...

SQL Query using Date retrieves Datetime values in a Node application connected to MSSQL

I am currently using version 6.3.1 of node mssql. My query involves multiple columns that are of type date. When querying in node mssql, the output for all Date columns is in this format: 2020-10-20T00:00:00.000Z However, when I execute the same query in A ...

The React Modal component seems to be malfunctioning within the context of Nextjs

Out of the blue, this issue popped up and I'm puzzled about why it's happening. I have two modals (with different names) that are identical in structure but only one is functioning properly. Both modals use the React-Modal library. The first moda ...