我想在vue.js中創建一個具有這樣結構的編輯器。如何在vuejs/vue.js中的contenteditable true div中的span標籤中調用keypress事件?
這是代碼片段:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ContentEditable problem in vue.js</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div id="editor"
contenteditable="true"
class="form-control"
style="height: 200px; overflow-y: auto">
<!-- @input="update($event,anyBlock)" if I put this inside the div tag it will call update method-->
<span @input="update($event,block1)">
<!-- This update method is not getting called
If we make this span tag contenteditable true and
put it inside a contenteditable false tag(say a span tag) it will work
But It will not give you feel like an editor, so please avoid that solution.-->
{{ block1.text }}
</span>
<span @input="update($event,block2)">
<!-- Not need to say. This has similar problem-->
{{ block1.text }}
</span>
</div>
</div>
<pre>
{{ $data }}
</pre>
</div>
</body>
<script src='https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.min.js'></script>
<script>
new Vue({
el:'.container',
data:{
block1: {
id: '1',
type: 'text',
text: 'Edit me id :1!'
},
block2: {
id: '2',
type: 'text',
text: 'Edit me id :2!'
}
},
methods: {
update: function (event, block) {
console.dir(event)
if (block.id === '1') {
this.block1.text = event.target.innerText
// If you call this function from div the whole text is going to be copied inside the div.
} else {
this.block2.text = event.target.innerText
}
}
}
})
</script>
</html>
但像往常一樣的按鍵,KEYDOWN,KEYUP事件在div,因爲它是CONTENTEDITABLE抓獲。
我不想使用
<span contenteditable="false">
<span contenteditable="true">
{{block1.text}}
</span>
</span>
<span contenteditable="false">
<span contenteditable="true">
{{block2.text}}
</span>
</span>
因爲這個塊編輯器內部的自由光標移動。
對於我的問題,最好的解決方案是什麼?
你可以使用JSFiddle來證明這一點嗎?我不是很清楚問題是什麼以及你想做什麼 – anthonygore
@anthonygore你是否熟悉vue js? –
看起來你需要的是模型綁定到HTML標籤的內部文本/ html。我相信Vue無法實現這一點(因爲它現在就是這樣) 您可能無法以{{block1.text}}這個值開始,而是必須將其賦值(在組件加載時加載)到元素innerHTML。 –