How to access vue.js 3 single file component functions from within a script tag

Imagine having a single file component structured like this:

<template>
  // content irrelevant
</template>

<script>
export default {
  data() {
    return {
      redLocations: [
        "Isfahaan",
        "Qom",
        "Tehraan",
        "Semnaan",
        ...
      ],
    };
  },
  methods: {
    colorize(paths) {
      paths.forEach((path) => {
        if (this.redLocations.indexOf(path.getAttribute("class")) !== -1) {
          path.setAttribute("class", "red");
        }
      });
    },
  },
};

window.onload = () => {
  const paths = document.querySelectorAll(".Provinces path");
  paths.forEach((path) => {
    if (this.redLocations.indexOf(path.getAttribute("class")) !== -1) {
      path.setAttribute("class", "red");
    }
  });
};
</script>
<style >
  ...
</style>

Is there a way to access the 'colorize' method outside of the 'export default' block, for example within the 'window.onload' event in this scenario?

Answer №1

To enhance efficiency, consider transferring the event listener declaration to the created lifecycle method within the component definition. This adjustment allows direct access to the colorize function utilizing this.colorize:

data() {...},
created () {
  window.onload = () => {
    const paths = document.querySelectorAll(".Provinces path");
    this.colorize(paths);
  }
},
methods: ...

Answer №2

Avoid using the onload event and instead utilize the mounted hook in Vue.js to handle the logic:

export default {
  data() {
    return {
      highlightedStates: [
        "California",
        "New York",
        ...
      ],
    };
  },
  methods: {
    highlight(paths) {
      paths.forEach((path) => {
        if (this.highlightedStates.indexOf(path.getAttribute("class")) !== -1) {
          path.setAttribute("class", "highlighted");
        }
      });
    },
  },
mounted(){
  const paths = document.querySelectorAll(".Map path");
   this.highlight(paths);
}
};

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

Photo uploading in ASP.NET MVC - encountering null HttpPostedFileBase issue

QUESTION: I'm having an issue where the Photo1 value is null in the controller post method despite uploading it. Can someone help with this? This is my model class: class ProductVM{ public string Name { get; set;} public string Color {get; ...

Verify if there are duplicate values present in a table

I have a Table that contains multiple rows, each row having input fields. I need to check for duplicate values within the table. Below is my code where I am currently checking for empty values, how can I modify it to also detect duplicate values? JavaScr ...

Retrieve a JavaScript file located in a separate folder

I'm facing an issue with a project that has the following layout: project | - public | - -index.html src | - -index.js The code I am using to import the file is as follows: <script src="../src/index.js"></script> H ...

"Exploring the world of Vue.js and videojs: refreshing the video

Is there a way to refresh the videojs in Vue (3)? Here is the code snippet I am currently using: <template> <video-js controls="true" preload="auto" ref="video_player" class="video-js vjs-big-play-centered&quo ...

Delay the rendering of the MUI DataGrid column until after the DataGrid is visible on the screen

Would it be feasible to asynchronously load a column of data in the MUI DataGrid after the table is displayed on the screen? Retrieving this additional data from the database is time-consuming, so I aim to have it appear once the table has fully loaded. T ...

Saving the index.html file to disk when the button is clicked

Is there a way to export the current HTML page to a file? I have attempted to achieve this using the following code, but it only works when the page is loaded and not with a button click. <?php // Start buffering // ob_start(); ?> <?php file_pu ...

Utilizing UTC Time with AngularUI's UI-Date Datepicker

My issue lies with the datepicker using localized time instead of UTC when making calls to the backend. To handle this, I've created a function that adjusts the value before posting it to the server: function adjustDateForTimeOffset(dateToAdjust) ...

Encountering an issue with a loop in my jQuery function - any solutions?

Having encountered an issue with a select object not working in my form-building function, I resorted to using an ajax call to fetch data from a database table. While the network tab in Chrome shows the data being retrieved successfully, the console displa ...

When trying to manually trigger the firing of the autocomplete function to get a place using Google API

My goal is to retrieve the data from autocomplete.getPlace() when triggering this event manually. Essentially, I have a function that captures the user's location in Lat/Lng format, and afterward, I aim to access other useful data using getPlace() su ...

Exploring Tmbd Movie Database with React.js - Results of searches will only display after the application is recompiled

Presented here is my component. The challenge I am facing pertains to the fact that upon entering a search query, no results are displayed until I manually save in the code editor and trigger a recompilation of the application. Is there a more efficient ap ...

What strategy should be employed to ensure that Javascript is operational upon completion of page loading?

I'm facing a challenge with running my JavaScript on my ASP.NET webform page. It seems like the elements are not fully loaded when the script runs, which could be causing issues. How can I use jQuery to ensure that my script is placed at the bottom of ...

When I click on the md-select element, a superfluous "overflow-y: scroll;" gets added to the <body> of my webpage

Typically, I have the following styles on my body: element.style { -webkit-app-region: drag; } However, when I interact with a md-select element (you can observe this behavior on the provided link), additional styles are applied. element.style { -w ...

Tips for using regular expressions with the find method in JavaScript?

Welcome to my Object: let data = [{ "title": "User info", "category": "personal", "userId": "abc12345" }, { "title": "Customer Info", "category": ...

Encountered an issue when attempting to select the password field in order to log into a Google account using

Having some trouble automating the login process for my Gmail account. Managed to find the email element with an ID, but hitting a roadblock trying to locate the Password element as it doesn't have an ID. Here's what I've attempted: passw ...

Unable to access the property 'function' of an undefined value

I've been attempting to call a function from another function within my React application. However, I am encountering an error that reads: Error in login TypeError: Cannot read property 'loadDashboard' of undefined. Despite researching simil ...

Failed to execute npm script for server side rendering (ssr)

I experimented with Server-Side Rendering (SSR) in my React application for SEO benefits. Although I encountered certain errors, they were not considered actual errors by React. Initially, the error appeared in componenDidMount=()=> Upon commenting ou ...

HTML and Javascript Form Integration for Sage Pay Purchase Button

Currently, I am working on a project that includes online payment options via PayPal and Google Wallet, with a "buy now" button. Now, my next step is to incorporate the Sage Pay "buy now" button onto the website using HTML and JavaScript. Although I have ...

How can data be transferred from a parent to a child component in Angular?

I'm facing an issue trying to pass the selected value from a dropdownlist in a user interface. I have a parent component (app.component.html) and a child component (hello.component.html & hello.component.ts). My goal is to transfer the option val ...

Is the JQuery ajax xhr fully completed before it begins?

Having a long script that can take a few minutes to execute, I decided to create a progress bar to display the current state. However, I encountered a problem where xhr evt.loaded/evt.total (30/30) returns 1 (100%) before the long script starts executing. ...

Moving information from a Vue.js component to a different container

Can I transfer some data? In my Vue component (child), I have: {{ checked.length }} This is responsible for the number of selected items. However, I need to display that information in another div (parent Vue) that is not within the view component. Upd ...