简体   繁体   English

脚本标签中vue.js 3单文件组件的调用方法

[英]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有没有办法访问“export default”之外的方法(在这种情况下是“colorize”)?(在这种情况下是“window.onload”事件

You can move the event listener definition to created lifecycle method, ie into the component definition, where you can access colorize with this.colorize :您可以将事件侦听器定义移动到created生命周期方法,即进入组件定义,您可以在其中使用this.colorize访问colorize

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

No need to add onload event just use the vue mounted hook to do that logic :无需添加onload事件,只需使用 vue 挂载钩子来执行该逻辑:

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);
}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM