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

How to create a responsive image that appears over a button when hovering in Bootstrap?

My goal is to display an image over a button when hovering. I've tried adding the .img-responsive class in Bootstrap while including the image in the HTML, but it's not working as expected with my current method of loading images. The buttons the ...

Generate a compressed file from a readable source, insert a new document, and transfer the output

The objective is to obtain an archive from the client, include a file, and transfer it to Cloud Storage without generating a temporary file. Both the client and server utilize the archiver library. The issue with the code snippet provided is that the file ...

Exporting variables in Angular's Ahead of Time (AoT) compiler is

I recently attempted to incorporate dynamic configuration into my project, following a guide I found in this insightful post. While everything functions smoothly with the JiT compiler, I encountered the following error when attempting to build using the A ...

Visualize data retrieved from a third-party website through scraping in a chart

After attempting to extract data from a website's data.asp file (formatted in json) and display it as a chart on my site using Google Chart API or FusionCharts, I'm facing issues. Although I can retrieve the json data, it doesn't render as a ...

Tips for quietly printing a PDF document in reactjs?

const pdfURL = "anotherurl.com/document.pdf"; const handleDirectPrint = (e: React.FormEvent) => { e.preventDefault(); const newWin: Window | null = window.open(pdfURL); if (newWin) { newWin.onload = () => ...

"Implementing a feature in Angular to display only a single ul element at a time while iterating through a

In the image above, there is an Add Person button. When this button is clicked, a new row labeled Person 1 is created, and this process continues for each subsequent click. At the right end of every row, there is a share icon that, when clicked, should ope ...

Having trouble retrieving data from API in my Next.js application using getStaticProps or getServerSideProps

I'm facing an issue while fetching data from an API in my Next.js app using getStaticProps() or getServerSideProps(). The data is not being fetched and displayed as expected. Strangely, when I use fetch() within a component, the data retrieval works f ...

Converting JavaScript code to jQuery and integrating it into a WordPress website has become a common practice

I recently developed a working javascript function as shown below: function calc(A,B,SUM) { var one = Number(A); var two = Number(document.getElementById(B).value); if (isNaN(one)) { alert('Invalid entry: '+A); one=0; } if (isNaN(tw ...

Presenting a trio of distinct tables each accompanied by its own unique button option

I am attempting to create a functionality where there are 3 buttons and when a user clicks on one of them, it shows the corresponding table while hiding the other two. I have experimented with using getElementById to manipulate the display property of the ...

How to resolve preventDefault issue on else condition during form submission in CoffeeScript on Rails 4

After submitting a form, I have implemented a code to prevent the page from refreshing and perform different actions based on certain conditions. Everything works as expected except for one scenario where the page still refreshes after executing the ELSE c ...

"Building your own utilities in Nuxtjs: A step-by-step guide

Currently, I am using Nuxtjs version 2.15.4 and I am looking to update my Utils functionality. Currently, I am using a mixin for my utils but I would like to implement something similar to the following code snippet: import {func1 , func3} from '~/plu ...

Unable to get ng-submit function to work properly within the Laravel PHP framework

Hello everyone, I have an inquiry regarding Laravel/AngularJS. In my project, there is a form where users can post questions. However, when I click the submit button, no requests are sent (as per inspection in Google Chrome). Interestingly, the Log in int ...

I am encountering a problem with the app.patch() function not working properly. Although the get and delete functions are functioning as expected, the patch function seems to be

I am in the process of setting up a server that can handle CRUD operations. The Movie model currently only consists of one property, which is the title. Although I can create new movies, delete existing ones, and even search for a ...

What are the steps for releasing a collection of Vue.js components?

Currently, I am working on a project that involves a Vuex module and abstract components that users can extend. My goal is to clean up my codebase by separating this project into a well-tested module and publishing it on NPM. In order to achieve this, I ha ...

Updating React component props

After updating the state in a component and passing the new props into the child, I noticed that the child is not updating correctly and the defaultValue of the input is not changing. My initial thought was that using this.props could be the issue, so I sw ...

When using Vue.js and Laravel, the DOM does not accurately display the updated array data after an axios call

After countless attempts to solve this issue on my own, I have decided to seek help here. I am relatively new to programming and currently working with laravel + vue.js + mysql. My Approach My process involves fetching data through an Axios call and upd ...

Minifying HTML, CSS, and JS files

Are there any tools or suites that can minify HTML, JavaScript, and CSS all at once? Ideally, these tools should be able to: Identify links from the HTML document and minify the associated JavaScript and CSS. Remove any unused JavaScript functions and CS ...

Storing table rows in an array using Javascript

I've encountered a situation where I have a PHP script generating a string of table rows that is then returned via an AJAX request. This generated string consists of all the content enclosed within the tbody tags (<tr>1</tr><tr>2< ...

Is it necessary to alter the number of rows or columns in the table?

I'm having an issue with my code where the table is not changing the number of rows based on the selected input option. It seems to only read the first value of the select id and does not update the rows accordingly. Can someone help me identify the m ...

When executing `npm run start`, a blank page appears exclusively on the server

I recently set up a Vue landing page on my Mac. In the terminal, I navigated to the folder and executed "npm install" and "npm run dev", which ran without any issues. However, when trying to do the same on a managed server, I encountered challenges with t ...