javascript - 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”事件
解决方案
您可以将事件侦听器定义移动到created
生命周期方法,即进入组件定义,您可以在其中colorize
访问this.colorize
:
data() {...},
created () {
window.onload = () => {
const paths = document.querySelectorAll(".Provinces path");
this.colorize(paths);
}
},
methods: ...
推荐阅读
- asp.net-core - 将 JWT 令牌存储在内存中是否是一种好习惯
- c++ - 如何使用 CMake 自动链接 boost 库
- c - C、为什么我的自定义释放函数给我“指针被释放没有分配”错误
- sql - 发生值更改时,如何从 Oracle 表中接收实时通知?
- ios - Swift 扩展类型约束
- c# - 计算 2 列中的持续时间
- reactjs - 在 Redux reducer 中,如果 state 没有定义,你能立即返回初始状态吗?
- github - 在运行 Github 操作的工作流程时,Lerna 总是列出所有准备发布的包
- angular - 为什么 canLoad 函数在重新路由期间导致无限循环?
- ios - Xcode 无法识别“frame”和“addChild”是什么?