Skip to content

Call methods of vue.js 3 single file component in script tag

Lets say i have a single file component like this:

<template>
  // doesn't matter
</template>
<script>
export default {
  data() {
    return {
      redStates: [
        "Isfahaan",
        "Qom",
        "Tehraan",
        "Semnaan",
        ...
      ],
    };
  },
  methods: {
    colorize(paths) {
      paths.forEach((path) => {
        if (this.redStates.indexOf(path.getAttribute("class")) !== -1) {
          path.setAttribute("class", "red");
        }
      });
    },
  },
};
window.onload = () => {
  const paths = document.querySelectorAll(".Provinces path");
  paths.forEach((path) => {
    if (this.redStates.indexOf(path.getAttribute("class")) !== -1) {
      path.setAttribute("class", "red");
    }
  });
};
</script>
<style >
  ...
</style>

is there a way to access methods(in this case ‘colorize’) outside of ‘export default’?(in this case ‘window.onload’ event

Answer

You can move the event listener definition to created lifecycle method, i.e. into the component definition, where you can access colorize with this.colorize:

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