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

582 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST 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: ...
0
On

No need to add onload event just use the vue mounted hook to do that logic :

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");
        }
      });
    },
  },
mounted(){
  const paths = document.querySelectorAll(".Provinces path");
   this.colorize(paths);
}
};