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

How can the callback from C++ be successfully installed in the Javaobject window within QtWebkit?

I have successfully implemented HTML-JS to call a C++ method using QtWebkit. Now, I want to send a callback from the C++ method to the JavaScript window. How can I achieve this? Below is my code snippet. #include <QtGui/QApplication> #include <Q ...

Creating a JSON object from two arrays is a simple process

Consider the following two arrays: let values = ["52", "71", "3", "45", "20", "12", "634", "21"]; let names = ["apple", "orange", "strawberry", &q ...

What is the minimum number of lines that can be used for javascript code?

Currently, I am in the process of developing a custom JavaScript minifier. One question that has come up is whether it is necessary to insert line breaks after a certain number of characters on a single line, or if it even makes a difference at all? For i ...

What is the best way to display all of these JSON objects on a webpage given the current AJAX setup?

I need help figuring out how to display all the objects and their contents from a JSON file on a webpage when a button is clicked. I don't want to use console.log, I actually want it to show on the webpage but I'm unsure of how to do that. Please ...

Problem with Vuex state not getting refreshed

Why doesn't the store update the d3 state? <script> import HorizontalLinearityGraph from "@/components/HorizontalLinearityGraph"; export default { components: {HorizontalLinearityGraph}, data: () => ({ model: null, d1:[2 ...

Retrieve data from a URL using Angular 6's HTTP POST method

UPDATE: Replaced res.json(data) with res.send(data) I am currently working on a web application using Angular 6 and NodeJS. My goal is to download a file through an HTTP POST request. The process involves sending a request to the server by calling a func ...

Is it possible for JavaScript to create an object that, when accessed directly, will return a string or number, and when its property is accessed, it will return that

something like this: const object = { value: 'value', label: 'label' } object === 'value' // true, accessing it directly returns 'value' object.label === 'label' // true object.value === 'value&ap ...

Attempting to reduce the width of the dig when it reaches 400

I have a square element with a click event that increases its size by 50 pixels on each click. However, once it reaches a size of 400 pixels, the size decreases by 50 pixels with every click instead. Additionally, when the size of the square reaches 100 p ...

A pause of 5 seconds between every request in Node.js

Need Help with Delays in Node.js Request Queue I am facing an issue with my code that involves looping through more than 500,000 records in a database and requesting information from another server. I have managed to write all the necessary functions, but ...

Exploring the capabilities of Google Apps Script for looping and generating output

I have two spreadsheets named rawData and processedData. The content of rawData is as follows: Status Title Options Live Title1 Option1, Option2, Option3, Option4 Live Title2 Option1, Option2, Option3, Option4, Option5 Live Title3 Option1, O ...

Handling events for components that receive props from various components in a list

In my code, I have a component called PrivateReview which includes event handlers for updating its content. export default function PrivateReview(props) { const classes = useStyles(); const removeReviewAndReload = async () => { await ...

What is the method for designating the specific pages on which the stripejs script should be loaded?

The performance of the main-thread is being significantly impacted by Stripe's script, as illustrated in the image provided by Google Insights. https://i.stack.imgur.com/bmdJ2.png My concern is that the page currently experiencing issues does not ac ...

Eliminate the classes that were inserted through Jquery

I'm currently working on an accordion and I've encountered an issue with jQuery adding classes that I don't want. How can I prevent jQuery from adding certain classes? The code below is what I have, but for some reason, jQuery keeps adding t ...

Top method for achieving a smooth transition in a loading CSS3 animation

Having trouble implementing a fade in/fade out effect on a div with a CSS3 based login animation when a function is loaded. I have set up a jsfiddle but still can't get it to work. Any assistance would be greatly appreciated! http://jsfiddle.net/adam ...

Trigger a JavaScript function upon clicking a link

Is it possible to have a CMS that loads articles using ajax, where the article is loaded through a function with parameters, and when a certain link is clicked, it redirects to the target page and launches the function on that page? For instance, let' ...

Explore a variety of images within an array using Gatsby and Markdown documents

After spending more than 6 hours on this, I've decided to call it quits for today. However, I'm hoping someone out there might have a solution. The problem at hand is as follows: I'm trying to include an array of images in a Markdown file t ...

Steps for implementing AJAX to display a success function and update database results in real-time

I'm struggling with allowing my AJAX call to send data to my PHP file and update the page without a reload. I need the success message to display after approving a user, but their name doesn't move on the page until I refresh. The goal is to app ...

Passing a JavaScript variable to a URL parameter can be achieved by

Can anyone advise me on passing JavaScript string variables and displaying them in the URL? For instance, let's say the URL is "xyc.com". Upon populating a variable (a), I wish for that variable to appear in the address bar as URL = "xyc.com/?a=". Cur ...

Data in DynamoDB Local is deleted once the instance is shut down

My app is utilizing DynamoDB Local and I am facing an issue where it keeps deleting all the sample data each time I shut down the instance. This problem seems to be unique as I have not found any similar cases while searching for a solution. I typically ...

What is causing the behavior of this JavaScript code in the Execution Context?

I recently delved into the world of asynchronous programming in JavaScript and wanted to share some code for examination: const myPromise = () => Promise.resolve('Success!'); function firstFunction() { myPromise().then(res => console. ...