Esr*_*aad 5 javascript function onclick vue.js
我正在构建一个 vue 组件,我想通过在修改 innerHTML 时调用 onClick 属性来调用在 Vue 方法中定义的函数。但是,它给了我错误,“未定义 showModal”,如下所示。
这是我的 showModal 函数,我只是想控制一些数据以确保调用该函数:
methods: {
showModal: function() {
console.log("function is called")
//this.$refs.myModalRef.show();
//this.account=account;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我尝试通过 onclick 函数在 js 中调用该函数的地方:
var inputText = document.getElementById("fileContents");
var innerHTML = inputText.innerHTML;
for(var i=0;i<this.violations.length;i++){
var index=innerHTML.indexOf(this.violations[i]);
if(index>0) {
innerHTML = innerHTML.substring(0, index) +"<a href='#' onclick='showModal'>"+ "<span style=\"background-color: yellow\">" + innerHTML.substring(index, index + this.violations[i].length) + "</span>" + "</a>" + innerHTML.substring(index + this.violations[i].length);
inputText.innerHTML = innerHTML;
}
}
Run Code Online (Sandbox Code Playgroud)
错误: (index):1 Uncaught ReferenceError: showModal 未在 HTMLAnchorElement.onclick ((index):1) 中定义
我是否以错误的方式调用它?
谢谢!
编辑:
感谢@Ferrybig - 我知道我可以调用该函数,但是我还有另一个问题;我想将我正在将其 html 更改为函数的当前词传递给这样的函数: onclick='myMethod(violations[i])' 我尝试将 this.violations 数组设置为全局,如下所示:
window.violations=this.violations;
Run Code Online (Sandbox Code Playgroud)
但同样,(变量 i)是数组中当前单词的索引,它不是要传递给“myMethod”的全局变量,它表示(i 未定义)。我无法将 i 设置为全局变量,因为它是在循环中每次递增的索引。我想过将我正在编辑的标签的当前索引发送到函数“myMethod”,这样我就可以跟踪我所在的标签以及 vue 组件中的 html 知道它,但不知道如何做到这一点..
还有其他建议吗?
使用 Vue 模板时,您可以使用易于使用的语法来减少编程时间,强烈建议您开始使用 Vue 渲染页面。
如果你不能使用 Vue 渲染页面,您仍然可以使用其他糟糕的技术:
首先,首先为 created 添加一个 created 生命周期方法,它将 Vue 方法的引用移动到全局范围: created(){window.myMethod =this.myMethod;}
由于我们随后将该方法添加到全局作用域,因此您可以使用 mymethod在 vanilla onclick 处理程序中。
请注意,上述解决方法不支持 Vue 组件的多个实例,但支持它变得更加困难,在这种情况下,您应该真正使用适当的 Vue 组件。
您在调用中没有使用 Vue 处理程序。改成onclick@click
所以:
@click="showModal"
Run Code Online (Sandbox Code Playgroud)
或者,或者,
v-on:click="showModal"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5005 次 |
| 最近记录: |