簡體   English   中英

腳本標簽中vue.js 3單文件組件的調用方法

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

假設我有一個這樣的文件組件:

<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”事件

您可以將事件偵聽器定義移動到created生命周期方法,即進入組件定義,您可以在其中使用this.colorize訪問colorize

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

無需添加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