Executing a Component function within an "inline-template" in VueJS

VueJS version 1.9.0

app.js

require('./bootstrap');
window.Vue = require('vue');

Vue.component('mapbox', require('./components/mapbox.js'));

const app = new Vue({
    el: '#app'
});

components/mapbox.js

// initially from https://github.com/phegman/vue-mapbox-gl/blob/master/src/components/Mapbox.vue
export default {
    data() {
        return {
            _map: null
        };
    },
    props: {
        accessToken: {
            type: String,
            required: true
        },
        mapOptions: {
            type: Object,
            required: true
        },
        navControl: {
            type: Object,
            default: () => {
                return {
                    show: true,
                    position: 'top-right'
                };
            }
        },
        geolocateControl: {
            type: Object,
            default: () => {
                return {
                    show: false,
                    position: 'top-left',
                    options: {}
                };
            }
        },
        scaleControl: {
            type: Object,
            default: () => {
                return {
                    show: false,
                    position: 'top-left',
                    options: {}
                };
            }
        },
        fullscreenControl: {
            type: Object,
            default: () => {
                return {
                    show: false,
                    position: 'top-right'
                };
            }
        }
    },
    mounted() {
        const map = this.mapInit();
        this._map = map;
        this.registerEvents(map);
    },
    methods: {
        mapClicked(map, e) {
            console.log("clicked");
        },
        mapInit() {
            mapboxgl.accessToken = this.accessToken;
            if (!this.mapOptions.hasOwnProperty('container')) {
                this.mapOptions.container = 'map';
            }
            const map = new mapboxgl.Map(this.mapOptions);
            this.$emit('map-init', map);
            return map;
        },
        registerEvents(map) {
            map.on('load', () => {
                this.$emit('map-load', map);
            });
            map.on('click', e => {
                this.$emit('map-click', map, e);
            });
            map.on('render', () => {
                this.$emit('map-render', map);
            });
        }
    },
    beforeDestroy() {
        this._map.remove();
    }
};

index.blade.php

<mapbox 
    access-token="MY-ACCESS-TOKEN"

    :map-options="{
      style: 'mapbox://styles/mapbox/light-v9',
      center: [-96, 37.8],
      zoom: 3
    }"
    :geolocate-control="{
      show: true,
      position: 'top-left'
    }"
    :scale-control="{
      show: true,
      position: 'top-left'
    }"
    :fullscreen-control="{
      show: true,
      position: 'top-left'
    }"

    @map-click="mapClicked"

    inline-template>

        <div id="map"></div>

</mapbox>

From index.blade.php I'm trying to call

@map-click="mapClicked"
which is in components/mapbox.js's methods

But I'm getting the errors

▶ app.js:36934 [Vue warn]: Property or method "mapClicked" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

▶ [Vue warn]: Invalid handler for event "map-click": got undefined

  1. I know if I move the mapClicked to app.js:
    const app = new Vue({el: '#app', methods: {mapClicked(){..}}});
    It will works but I want my file clean and would try to avoid this solution.
  2. I read this: Vue inline template not finding methods or data but it did not work for me.

Answer №1

When the inline-template attribute is added to a component's tag, all content inside that tag becomes the template for the component and is scoped to the Vue instance of that component. However, the tag itself remains scoped to the parent component. The warning message is simply indicating that the parent component does not contain a mapClicked method.

To resolve this issue, you can directly call the mapClicked method within the click handler defined in the registerEvents method:

map.on('click', e => {
  this.mapClicked(map, e);
  this.$emit('map-click', map, e);
});

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

Leveraging *ngFor to extract HTML content from ion-label

I've encountered an issue while using *ngFor in my HTML like this: <ion-slides #slides [options]="slideOpts"> <ion-slide class="numbers-wrapper" *ngFor="let questionNumber of numbers" (click)="clickQue ...

Dynamically obtaining the screen width in JSP using a variable

Could someone provide assistance on how to resize an image using an img src="blah.jpg?width=x" so that my page can be displayed at various sizes? I just need x (width) as a JSP variable. Update 2021: It's been 9 years since this question wa ...

JQuery enthusiast seeks cheerful clicker for callback upon event binding

Incorporating a complex functionality into a click event is proving to be challenging $(someSelector)).bind('click', someFunction(a,b,c)); function somefunction(a,b,c) { return function() { // dive into complexity $(anotherS ...

Obtaining information from a local JSON file in AngularJS

I'm facing some issues with retrieving data from a JSON file using the structure below. In my controller.js file, I've written: var controllers = angular.module('hotels.controllers', []); controllers.controller('AppCtrl', f ...

What is the best way to retrieve ul li values using AngularJS?

I am looking to extract the content of li elements within a ul element in an AngularJS controller and save them into an array. Sample HTML Code: <ul id="list" my-directive> <li>A</li> <li>B</li> <li>C ...

Tips on maximizing efficiency in number game coding

Seeking to create a number using a specified set of 6+ inputs. For instance, aiming for the number 280 with inputs [2,4,5,10,30,50,66], the desired output format would be something like this: ((2+5) * 4 * 10). Each input number can only be used once per s ...

Does the triple equal operator in JavaScript first compare the type of the value?

When using the triple equal operator, it not only measures the value but also the type. I am curious about the order in which it compares the value and returns false if they do not match, or vice versa. ...

Attempting to retrieve exclusively the checked records in Vue.js

Currently, I am referring to this library for checkboxes. As I delve into the code, I notice how it is declared and utilized. Initially within the el-table, we have @selection-change="handleSelectionChange". They have initialized an empty array ...

When an answer is provided in Inquirer.js, pressing Enter is causing the process to terminate

Currently, I am working on creating a Command Line Interface (CLI) using the NPM package called Inquirer. It has been a useful tool so far, but I have encountered an issue. The interface functions correctly in terms of posing questions to the user, but onc ...

Unpacking a props object results in an undefined value

I've been struggling to set up a data-grid in react because I'm facing issues with accessing the data from my props. Whenever I try to access or destructure the prop, it shows up as "undefined" in my console. This problem only arises when the p ...

What is the best way to add uppercase letters exclusively?

Is there a way to dynamically style uppercase text within an <h2> tag that is generated based on an image's alt text? I'm thinking of using javascript / jquery to identify the uppercase text and encase it in a <strong> tag, then appl ...

Encountering difficulty in implementing two modals simultaneously on a single web page while utilizing the useDisclosure() hook in Ch

ChakraUI provides a custom hook called useDisclosure() which gives you access to isOpen, onClose , onOpen. const { isOpen, onOpen, onClose } = useDisclosure() You can use the onOpen function as an onClick handler for a button to open a modal. <Modal ...

Integrate new functionality into the plugin's JavaScript code without directly editing the JS file

I need to incorporate a new function called 'setInputDataId' at the same level as the existing function '_select' in the plugin js file without directly modifying the file itself. I am seeking guidance on how to add this new function. ...

Lacking the knowledge on establishing range for amCharts

I am currently utilizing the amcharts plugin to generate visually appealing charts. While browsing through its features, I came across a few interesting ways to add ranges. However, I noticed that the structure of the code for these charts is different fro ...

Guide to excluding all subdependencies using webpack-node-externals

My current setup involves using webpack to bundle both server assets and client code by specifying the target property. While this configuration has been working well, I encountered an issue where webpack includes all modules from node_modules even for ser ...

How do I go about updating my code for welcome messages from discord.js v12 to v13?

While watching a YouTube tutorial on welcome messages, I decided to copy the entire code. However, when I tried using this code with discord.js v13, it didn't work. Strangely enough, everything seemed to function perfectly fine with discord.js v12. In ...

create a custom function to trigger when a new item is added to a Vuejs data property

Currently, I have a Vuejs application that is relatively simple as I am still in the learning process of Vuejs. My goal is to trigger another function whenever I add or delete from a specific data property. Here is an example code snippet: data: { prici ...

Troubleshooting a JQuery AJAX Autocomplete problem involving PHP and MySQL

I am facing an issue with my autocomplete feature. It is functioning properly on one of my pages, but not on this particular page. Even though the correct number of entries is being retrieved, they all appear to be "blank" or are displayed in black text th ...

After an ajax request, the Jquery hover effects are no longer functional

On my website, I have implemented ajax calls to filter product results and apply effects. However, the effects on these products seem to stop working after the ajax call is completed. Located at the bottom of the page's code is the following script: ...

``Next.js allows you to nest components within a component to create routing functionalities

My login page has 3 different roles for logging in: Admin, Student, and Company. Instead of redesigning the entire page, I just want to update the login component for each specific role. Login Page export default function Authpage(){ return( ...