我正在构建一个vue组件,并且希望在修改innerHTML时通过调用onClick属性来调用在Vue方法中定义的函数。但是,它给出了错误,"showModal未定义“,如下所示。
这是我的showModal函数,我只是试图控制一些数据,以确保该函数被调用:
methods: {
showModal: function() {
console.log("function is called")
//this.$refs.myModalRef.show();
//this.account=account;
}
}
这里是我试图通过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;
}
}
错误:(索引):1未捕获索引:未在HTMLAnchorElement.onclick ((索引):1)定义ReferenceError: showModal
我是不是叫错了?
谢谢!
编辑:
感谢@Ferrybig -我知道我可以调用这个函数,但是我有另一个问题;我想传递当前的单词,我正在将其html更改为如下函数: onclick='myMethod(violationsi)‘我尝试将this.violations数组设置为全局数组,如下所示:
window.violations=this.violations;
但同样,(变量i)是数组中当前单词的索引,它不是要传递给'myMethod‘的全局变量,它说(i未定义)。我不能将i设置为全局变量,因为它是循环中每次递增的索引。我考虑将我正在编辑的标记的当前索引发送到函数'myMethod',这样我就可以跟踪我在哪个标记中,并通过vue组件中的html识别它,但不确定如何做到这一点。
还有其他建议吗?
发布于 2019-04-10 14:15:45
在使用Vue模板时,您可以使用易于使用的语法来减少编程时间,并且强烈建议您开始使用Vue渲染页面。
在无法使用Vue渲染页面的情况下,您仍然可以使用其他糟糕的技术:
首先,为created添加一个创建的生命周期方法,该方法将Vue方法的引用上移到全局作用域:created(){window.myMethod =this.myMethod;}
由于我们随后将该方法添加到了全局作用域中,因此您可以在普通的onclick处理程序中使用mymethod
来引用它。
请注意,上面的变通方法不支持Vue组件的多个实例,但支持它会变得更加困难,在这种情况下,您应该真正使用适当的Vue组件。
发布于 2019-04-10 03:58:23
您没有在调用中使用Vue处理程序。将onclick
更改为@click
所以:
@click="showModal"
或者,或者,
v-on:click="showModal"
发布于 2019-04-10 11:53:38
你必须像Method Event Handlers一样使用Vue语法onClick,所以
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);
需要更改以
innerHTML = innerHTML.substring(0, index) +"<a href='#' v-on:click="showModal">"+ "<span style=\"background-color: yellow\">" + innerHTML.substring(index, index + this.violations[i].length) + "</span>" + "</a>" + innerHTML.substring(index + this.violations[i].length);
https://stackoverflow.com/questions/55600042
复制相似问题