Having difficulty replacing a method within the Vue constructor

There's a component with a method that is called upon creation. It utilizes the vue-select library, but the specific purpose of this component is not relevant to the issue at hand.

<template>
    <v-select :on-change="onchangecallback"></v-select>
</template>

<script>
    import Vue from 'vue'
    import vSelect from 'vue-select'

    Vue.component('v-select', vSelect);

    export default {
        methods: {
            onchangecallback: () => {alert('default')}
        },
        created: function() {
            this.onchangecallback();
        }
    }
</script>

In another file, I import this component and create a new instance using the Vue constructor. I pass in a new onchangecallback method, expecting it to override the default one:

import VSelect from './components/ui/VSelect.vue';

new Vue({
    VSelect,
    el:         '#app',
    components: {VSelect},
    template:   `<v-select />`,
    methods:    {
        onchangecallback: () => {alert('custom')} // doesn't work
    }
});

However, when I run the app, instead of displaying alert('custom'), I still see alert('default').

Answer №1

I'm unsure of the objective you're aiming for.

However, I have a solution available at https://codesandbox.io/s/16ab7cd3j6

To pass your new callback function to that component, you need to define a prop (and use it as the argument).

 props: {
    customcallback: {
      type: Function,
      default() {
        return function() {
          alert('default');
        };
      },
    },
  },
  created: function() {
      this.customcallback();
  }

Make sure to utilize it instead of the default option.

Review all code within the snippet provided above.

Answer №2

For effective communication between components, it is recommended to utilize events. Emitting an event in a child component allows the parent component to listen and respond:

Child Component:

created() {
    this.$emit('change')
}

Parent Component:

Template:

<child-component v-on:change="doSomething" />

Methods:

methods: {
    doSomething() {
        // handling logic goes here
    }
}

Explanation

Within the child component, you emit an event named "change" whenever a change occurs. In this scenario, it happens upon the component's creation.

The parent component specifies that when the child component emits a "change" event, it should execute the "doSomething" method defined in the parent component.

This approach is commonly applied, for instance with inputs triggering an "input" event whenever their content changes, allowing any parent components to handle the event using v-on:input="methodHere".

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

Calling sequence of AWS Lambda function with Node.js

Here is a simplified version of AWS lambda code snippet: 'use strict'; var aws = require('aws-sdk'); var docClient = new aws.DynamoDB.DocumentClient(); exports.handler = (event, context, callback) => { var inputorder = initIn ...

Tips for excluding specific codes from running in BeforeAll for a specific Describe() block in Jasmine

Currently, I am in the process of writing a Jasmine unit test spec. The JS file contains several describe() blocks. Within the BeforeAll function, my objective is to execute a function only for the "A" and "C" Describe-Blocks. How can this be accomplished ...

Controller fails to initialize when utilizing $location.path or $state.go

Issue with Controller Initialization after Redirect in Ionic App I have encountered an issue where the controller is not initializing on the same page when I use $state.go or $location.href. In my Ionic app, I am using a sidemenu to pass category Id to th ...

Find all instances of Javascript comments and delete them using Regular Express

Hey there! I'm currently working on removing all JavaScript comments (//) within the HTML document. Take a look at this example: <html> <img src="http://example.com/img.jpg" /> <script> //Some comments gallery: { enabled: t ...

Plupload is not compatible with ng-dialog

I'm currently attempting to integrate plupload into a modal window that is generated by ng-dialog. Here is the code I am using: $scope.showManager = function(){ ngDialog.open({ template: '/template/fmanager.html', controller: &apo ...

Rendering a Vue component in various locations within the parent template

Currently, I am in the process of creating a responsive navbar component that incorporates a child component. One challenge I am facing is the need to display this component differently based on whether the user is on a mobile or desktop device. The curren ...

Enhance user experience with dynamic color changes in JavaScript

Looking to create a navigation menu with unique colors for each selected state? Check out the code below! After searching extensively, I stumbled upon this snippet. While it only includes one selected state, you can easily customize it for three different ...

iPhone users experiencing issue with Bootstrap Modal failing to open

My website utilizes a BS Modal that successfully opens on laptops and mobile simulators such as Safari Responsive Design Mode. However, when accessed from a physical mobile device (iOS 11 iPhone X), the modal fails to open. Check out the page ...

Prevent immediate propagation of multiple events occurring on the same element

When it comes to an element, I have implemented two click events. One of them is a delegated event, while the other is not. $( document ).on( 'click.bar', 'p', function( e ) { console.log( 'click.bar', e ); e.stopIm ...

Obtaining a cloned HTML object using jQuery in C# the correct way

In my webpage, there is a div with various input elements inside. I want to duplicate the entire HTML content of this div so that I can store it in my database. When I retrieve this cloned HTML in the future, I want it to appear on another page exactly as ...

To make sure that async tests and hooks are properly handled, remember to call "done()" after completion. If you are returning a Promise, make sure that it resolves properly for puppeteer and

I am currently testing my component using mocha and Google Puppeteer. In my unit test file, I have set up the Puppeteer browser to launch before the tests and close after the tests in the respective functions. However, when running the test file, I encou ...

Creating a responsive Google map within a div element: A step-by-step guide

I am experiencing difficulties with implementing a responsive Google map on my webpage. To achieve a mobile-first and responsive design, I am utilizing Google Map API v3 along with Bootstrap 3 CSS. My objective is to obtain user addresses either through th ...

Exploring Vue Router: Navigating with Different Components on the Same Path

When using Vue 3 Composition API, if the components for paths "/users" and "/users/user-reference" are completely different and unrelated, how should I structure the router configuration? Possible Solutions: const routes = [ { path: '/users', ...

Windows authentication login only appears in Chrome after opening the developer tools

My current issue involves a React app that needs to authenticate against a windows auth server. To achieve this, I'm hitting an endpoint to fetch user details with the credentials included in the header. As per my understanding, this should trigger th ...

Attaching an event listener to a DOM element that has not been created yet

I have a collection of <div class="location-box" data-location-id="123"> <img src="img_url" /> </div> Inserted into the .locations container. I would like to implement a feature where clicking on a .locati ...

What is the best way to ensure that the checkbox is not affected when you click on the area?

If the user interacts with the checkbox, I don't want the handleClick function to execute. Is there a way to exclude it or prevent the click event from triggering? <div ... onClick={this.handleClick}> <div> some content here < ...

What is the best way to align geometry at the bottom of the screen in Three.js while still preserving its aspect

I recently started using Threejs and encountered an issue with positioning geometry. I'm trying to place the geometry at the bottom with half of it cut off, so only half should be visible. However, when I use position.setY(-300), the geometry moves do ...

Using PHP, HTML, and JavaScript to generate a dropdown list from a database

I am looking to create a dynamic dropdown list populated from a database using JavaScript. My goal is to design a form where users can add multiple rows by clicking the "add more" button. The form will include both a text input field and a dropdown list. ...

jquery disable document manipulation function

I need to make some updates to a simple function that involves the current textarea. $(document).on("keydown", updated_textarea_var, function (e) { // do stuff }); To achieve this, I tried disabling the previous function and running a new one w ...

Managing location markers with Google Maps API V3: Saving and removing locations

I encountered an issue while using GMAP V3. After realizing the need to save map changes in a database, I struggled to find a way to accomplish this task. Before attempting any workarounds, I thought it would be best to gather some ideas first. The communi ...