我正在尝试在加载VueJS后向我的viewmodel添加事件侦听器。如果我不使用VueJS,添加事件监听器是有效的,所以我知道代码是正确的,但它们从不在VueJS中附加。
<div id="app">
<div name="pageContent" id="preview">
<section class="row">
<div class="columns medium-12">
<h1>This is the top content</h1>
<p>ashcbaubvdiuavduabd</p>
</div>
</section>
<section class="row">
<div class="columns medium-6">
<h1>This is left content</h1>
<p>ashcbaubvdiuavduabd</p>
</div>
<div class="columns medium-6">
<h1>This is the right content</h1>
<p>ashcbaubvdiuavduabd</p>
</div>
</section>
</div>
</div>
<script type="text/javascript">
let editorContainer = document.getElementById('preview');
let controls = document.getElementById('defaultControls');
let cmsEditor = new CmsEditor(editorContainer, controls);
var app = new Vue({
el: '#app',
data: {
editor: cmsEditor
},
mounted: function() {
// wire up our listeners
console.log('mounted')
document.oncontextmenu = function () { return false; };
let rows = this.editor.EditorContainer.getElementsByTagName("section");
for (var i = 0; i < rows.length; i++) {
console.log("section " + i + " : " + rows[i].innerHTML);
rows[i].addEventListener('mouseover', function () {
console.log('mouse over event');
this.editor.SetActiveRow(this);
});
rows[i].addEventListener('dblclick', function () {
this.editor.DisplayContextMenu(this);
});
}
},
methods: {
save: function () {
console.log('save');
this.editor.Save();
},
undo: function () {
console.log('undo');
this.editor.Undo();
}
}
});
</script>
答案 0 :(得分:3)
看起来您正在为将从DOM中删除的元素创建编辑器。 Vue使用#app
的内容作为模板,将模板编译为渲染函数,然后用渲染函数的结果替换DOM。鉴于编辑器是在现在已经消失的DOM元素上创建的,我希望代码会失败。
您可能希望将编辑器的创建移动到mounted
,然后设置您的事件监听器。
FWIW,我也认为你有评论者提到的this
问题。
我认为它应该是这样的:
mounted: function() {
let editorContainer = document.getElementById('preview');
let controls = document.getElementById('defaultControls');
this.editor = new CmsEditor(editorContainer, controls);
// wire up our listeners
console.log('mounted')
document.oncontextmenu = function () { return false; };
let rows = this.editor.EditorContainer.getElementsByTagName("section");
for (var i = 0; i < rows.length; i++) {
console.log("section " + i + " : " + rows[i].innerHTML);
rows[i].addEventListener('mouseover', () => {
console.log('mouse over event');
this.editor.SetActiveRow(this);
});
rows[i].addEventListener('dblclick', () => {
this.editor.DisplayContextMenu(this);
});
}
},