首页 > 解决方案 > vue.js 3 单文件组件在script标签中的调用方法

问题描述

可以说我有一个像这样的文件组件:

<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>

有没有办法在“export default”之外访问方法(在这种情况下是“colorize”)?(在这种情况下是“window.onload”事件

标签: javascriptvue.jsvuejs2vue-componentvuejs3

解决方案


您可以将事件侦听器定义移动到created生命周期方法,即进入组件定义,您可以在其中colorize访问this.colorize

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

推荐阅读