script标签中vue.js3个单文件组件的调用方法
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);
}
};
假设我有一个像这样的单个文件组件:
<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);
}
};