Accessing Child HTML Elements with VueJS2

When working with Vue, I usually use the ref keyword to access components. However, I am struggling to understand how to access HTML tags from within a component.

I attempted:

<input type="text" ref="searchAddress" id="searchAddress" name="searchAddress" class="form-control" v-model="incidentForm.searchAddress">

and within the vue component:

var input = this.$refs.searchAddress;

This approach did not work for me, leading me to believe that it only works when referencing components. How can I access the input tag from within Vue?

I have created a class to manage all GoogleMaps API calls in my Vue files. Therefore, I am unsure of how to handle accessing the data of a specific input field without direct access. What would be the correct approach to avoid direct access like this?

The error message I am encountering is:

Uncaught TypeError: Cannot set property 'autocompletePlace' of undefined
. It seems that this.autocompletePlace = place is not functioning as expected.

methods: {
        initMap: function initMap() {
            this.initialLocation = this.createInitialLocation(48.184845, 11.252553);
            this.mapSetup(this.$refs.map, this.initialLocation, function () {
                this.initAutoCompleteListener(function (place) {
                    this.autocompletePlace = place;
                });
            }.bind(this));
        }
    }

GoogleMapsApi.js

export default {
    data() {
        return {
            map: '',
            currentIncidentLocation: '',
            autocomplete: '',
            searchMarker: ''
        }
    },

    events: {
        currentIncidentLocation: function(location) {
            this.currentIncidentLocation = location;
        }
    },

    methods: {
        createInitialLocation: function(latitude, longitude) {
            return new google.maps.LatLng(latitude, longitude);
        },

        mapSetup: function(selector, initialLocation, callback) {
            this.map = new google.maps.Map(selector, {
                zoom: 10,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
            });
            this.map.setCenter(initialLocation);
            this.searchMarker = this.createMarker();
            var input = document.getElementById('searchAddress');
            this.autocomplete = new google.maps.places.Autocomplete(input);
            callback();
        },

        initAutoCompleteListener: function(callback) {
            this.autocomplete.addListener('place_changed', function() {
                var place = this.autocomplete.getPlace();
                if (!place.geometry) {
                    window.alert("The place could not be found");
                    return;
                }
                callback(place);
            }.bind(this));
        },

        createMarker: function() {
            var marker = new google.maps.Marker({
                map: this.map
            })
            return marker;
        }
    }
}

GISView.vue

<template>
    <div ref="map" id="map" class="google-map" style="height: 800px; position: relative; overflow: hidden;">
    </div>
</template>

<script>
    import GoogleMaps from '../mixins/GoogleMaps.js';

    export default {
        mixins: [GoogleMaps],

        data() {
            return {
                initialLocation: '',
                autocompletePlace: ''
            }
        },

        mounted() {
            this.$events.$on("MapsAPILoaded", eventData => this.initMap());
        },

        methods: {
            initMap: function() {
                this.initialLocation = this.createInitialLocation(48.184845, 11.252553);
                this.mapSetup(this.$refs.map, this.initialLocation, function() {
                    this.initAutoCompleteListener(function(place) {
                        this.autocompletePlace = place;
                    })
                }.bind(this));
            }
        }
    }
</script>

Answer №1

The outer function has been bounded, but the inner one is still unbound. You can try

this.bindOuterFunction(function(data) {
     this.innerData = data;
}.bind(this))

Answer №2

To utilize HTML tags with $refs, follow this example:

<template>
  <div class="sample">
    <input
      type="email"
      id="emailInput"
      name="emailInput"
      class="form-control"
      ref="emailInput"
      placeholder="Email Address"
      v-model="emailModel">
  </div>
</template>

<script>
  import Greetings from './components/Greetings'

  export default {
    name: 'main',

    data() {
      return {
        emailModel: ''
      }
    },

    mounted() {
      const element = this.$refs.emailInput
      console.log('Reference to input element: ', element)
      console.log('Placeholder attribute from the reference element: ', element.placeholder) // displays "Email Address"
    }
  }

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

Is it possible for a Vue data property to have a value that is determined by another Vue data property object?

Within my HTML form, I have implemented the flatPickr (calendar picker) component which generates an input field. I am currently exploring how to dynamically change the class of the input field if the error class function returns true. Below is the flatPi ...

When using Vuelidate custom validation, errors are displayed on each individual element within the $each function

My data object formData has the structure outlined below: { name: '', defaultPort: 1000, protocolPorts: [{ manual_ports: [] }] } The manual_ports array consists of strings that can be dynamically added. I need to validate each port ...

Creating a function in React to be passed as a prop

Recently, I was given the task of enhancing a user interface as a small challenge to help me dive into the world of programming. My goal is to incorporate a date picker into my search bar to allow users to filter their search results by selecting specific ...

Angular's sanitization script incorrectly modifies the URL value provided in the script src attribute

How can I safely sanitize an external URL to dynamically load a script and remove scripts for a specific component only? Here is the approach I have used: private sanitizeUrl(): SafeResourceUrl { // Value declared in the environment file return ...

One way to generate div elements based on the number in an input field when a button is clicked, but ensuring it only happens once

What I am attempting to achieve is: Retrieve data from a JSON file upon button click. Display the data in separate boxes, each one different for every element of the array. For instance, if the JSON provides 3 rows of data, there should be 3 distinct box ...

I am having trouble adding multiple items on different occasions - is it something to do with JQUERY

I have been working on a dynamic website that loads Firebase values into a table. However, I encountered an issue where the data does not appear when going back to the orders page after visiting another page. After some testing, I found that placing a but ...

Highlight the active page or section dynamically using HTML and jQuery - How can it be achieved?

What am I trying to achieve? I am attempting to use jQuery to dynamically highlight the current page from the navigation bar. Am I new to jQuery/HTML? Yes, please excuse my lack of experience in this area. Have I exhausted all resources looking for a sol ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...

Locate and dismiss a toast message (Toastr)

I have a webpage where I can add multiple popup notifications called toasts dynamically using the toastr plugin found at https://github.com/CodeSeven/toastr. Each toast has an Ok link that, when clicked, should only close that specific toast and not all v ...

Checkbox paired with a read-only text column

I have a simple HTML input field with JavaScript functionality, which includes a checkbox. I am trying to write text in the input field when the checkbox is checked, and make the input field read-only when it is not checked. Can anyone provide an example ...

The test suite encountered an error (EBUSY: resource busy or locked) and unfortunately failed to run at Nx version 14.5.10 and Jest version 27.5.1. It seems there was an

I have recently upgraded my NX Monorepo from version 13 to 14, and everything seems to be working fine except for the Jest migration. I keep encountering this error even after trying various solutions like clearing the cache, deleting node_modules, and rei ...

The utilization of 'ref' with React Styled Components is proving to be ineffective

Using refs in Styled Components has been tricky for me. When I attempt to access them in my class methods as shown below, I encounter the error message: Edit.js:42 Uncaught TypeError: this.....contains is not a function constructor(props) { .... ...

Troubleshooting the issue: JavaScript's Time comparison failure with JSON versus Local time

Dealing with JSON data like the following: [ { "hourly_AQI": 73.0, "hourly_date": "Tue, 31 Oct 2023 11:00:00 GMT" }, { "hourly_AQI": 79.0, "hourly_date": "Tu ...

What is the best way to test a JavaScript function that includes nested timeouts using Jasmine?

I have a function that clears an input on blur. It's designed for use with Angular Materials, and I've created a directive for when this functionality is needed. function clearTextOnBlurLink(scope, element, attrs, controller) { $timeout(f ...

Store text in a table format in your local storage

I need help figuring out how to save product and price information to local storage when an "add to cart" button is pressed. Can someone provide guidance on how to do this? Here is the code I currently have: body> <!-- Header--> ...

Is Next.js experiencing issues with animating presence specifically for exit animations?

I'm facing an issue with adding an exit animation to my components in next js. Despite setting an initial animation, the exit animation doesn't seem to work as expected. Could someone please help me figure out what I'm doing wrong here? Be ...

The MUI Autocomplete filterOptions is not effectively filtering out all options as expected

Hey there! I'm facing an unusual situation with my Autocomplete feature, which has been heavily customized to meet certain restrictions and requirements. The issue I am encountering is related to filtering. Despite successfully filtering the results ...

Troubleshooting issue: Inability to assign classes to child elements within divs of a designated class

Currently, I am facing an issue while attempting to insert divs into multiple divs that share a common class called ".description". My goal is to assign a unique class to each internal div, but for some reason, this only seems to work for the first div w ...

Can you tell me the alternatives for getServerSideProps and getStaticProps in Next.js version 14?

I'm trying to wrap my head around the rendering behavior of SSR/SSG/ISR in Next.js version 14 with the updated app router. Previously, Next.js provided predefined functions like getServerSideProps for server-side fetching and processing (SSR), or getS ...

Using jQuery to fetch data asynchronously

I am currently dealing with a web application that needs to carry out the following task. It must send GET requests to a web service for each date within a selected date range, yet this process can be time-consuming. Since I plan to visualize the retrieved ...