【问题标题】:Call methods of vue.js 3 single file component in script tagvue.js 3 单文件组件在script标签中的调用方法
【发布时间】:2021-01-13 01:24:09
【问题描述】:

假设我有一个像这样的单个文件组件:

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

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vuejs3


    【解决方案1】:

    无需添加 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);
    }
    };
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-03
        • 2021-01-24
        • 1970-01-01
        • 2022-01-25
        • 2022-10-23
        • 1970-01-01
        • 2018-03-13
        相关资源
        最近更新 更多