1
我想添加事件監聽器到我的viewmodel一旦VueJS加載。如果我不使用VueJS,添加事件監聽器就可以工作,所以我知道代碼是正確的,但他們從不附加在VueJS中。添加事件監聽器在VueJS 2
<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>
在Vue公司活動從DOM事件不同。您沒有註冊任何Vue事件。你的回調不起作用,因爲你正在訪問錯誤的'this'。 – thanksd
[如何在回調中訪問正確的\'this \'](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) ) – thanksd
如果您使用的是ES6,請使用箭頭函數,以便詞彙'this'(即VueJS實例的)被綁定。否則,你將不得不將它緩存在事件監聽器之外,例如'var self = this',這樣在事件監聽器中你可以正確地引用你的Vue實例,例如'self.editor.SetActiveRow(這)'。 – Terry