Reputation: 308
My problem is to replace the value of a computed property by the input made by a user. My setup is like this:
html
<div class="col-md-3">
<ul style="margin-top: 50px">
<ol v-for="note in notes">
<h3 @click="setActive($index)">{{note.name}}</h3>
</ol>
</ul>
</div>
<div class="col-md-9" v-show="activeNote">
<h2 v-show="nameIsText" @click="switchNameTag()">{{activeNote.name}}</h2>
<input class="form-control" v-show="!nameIsText" @keyup.enter="switchNameTag()" value="{{activeNote.name}}">
<textarea name="note-text" class="form-control" rows=10>{{activeNote.text}}</textarea>
</div>
js
<script>
var vm = new Vue({
el: 'body',
data: {
active: {},
nameIsText: true,
notes: [{
id: 1,
name: 'Note 1',
text: 'Text of note 1'
}, {
id: 2,
name: 'Note 2',
text: 'Text of note 2'
}, {
id: 3,
name: 'Note 3',
text: 'Text of note 3'
}, {
id: 4,
name: 'Note 4',
text: 'Text of note 4'
}, {
id: 5,
name: 'Note 5',
text: 'Text of note 5'
}]
},
methods: {
setActive: function(index) {
this.active = index;
},
switchNameTag: function() {
this.nameIsText = !this.nameIsText;
},
},
computed: {
activeNote: function() {
return this.notes[this.active];
},
},
});
</script>
I've made a simple note-app, if you click one note, a textarea with the text and a heading 2 with the name is displayed.
Now if you click the name within the <h2></h2>
-Tags, the heading 2 is replaced by an input field - so the user can edit ne name of the current note.
Everything works, except the fact, that when I edit the name in the input field (the name is a computed property) the name isn't updating. A second problem is, if I click another note after editing the name of one note, the name of the old note remains in the input field instead of showing the name of the newly clicked note.
I've added two pictures for better understanding:
So my (probably related) questions are, how can I edit the computed property in the input field, and display the name of a newly clicked note even if I haven't hit enter after editing the name in the input field?
Upvotes: 0
Views: 3069
Reputation: 43881
You want to use the v-model
binding for the items you're editing. These give you the two-way binding that will actively update the underlying data items.
Also needed to use v-if
instead of v-show
because activeNote
can be undefined, in which case accessing its members is an error.
<div class="col-md-9" v-if="activeNote">
<h2 v-show="nameIsText" @click="switchNameTag()">{{activeNote.name}}</h2>
<input class="form-control" v-show="!nameIsText" @keyup.enter="switchNameTag()" v-model="activeNote.name">
<textarea name="note-text" class="form-control" rows=10 v-model="activeNote.text"></textarea>
</div>
Upvotes: 1