I want to get the innerText
of an item in a rendered list, but accessing it using this.$refs
doesn't seem to work. I've also tried to use v-modal
and that doesn't seem to work either.
Here's my code:
<div id="simple" v-cloak>
<h1>Clicked word value!</h1>
<ul>
<li v-for="word in wordsList" @click="cw_value" ref="refWord">
{{ word }}
</li>
<h4> {{ clickedWord }} </h4>
</ul>
</div>
var app = new Vue({
el: '#simple',
data: {
clickedWord: '',
wordsList: ['word 1', 'word 2', 'word 3']
},
methods: {
cw_value: function() {
this.clickedWord = this.$refs.refWord.innerText
// "I don't know how to get inner text from a clicked value"
}
}
})
I want to get the innerText
of an item in a rendered list, but accessing it using this.$refs
doesn't seem to work. I've also tried to use v-modal
and that doesn't seem to work either.
Here's my code:
<div id="simple" v-cloak>
<h1>Clicked word value!</h1>
<ul>
<li v-for="word in wordsList" @click="cw_value" ref="refWord">
{{ word }}
</li>
<h4> {{ clickedWord }} </h4>
</ul>
</div>
var app = new Vue({
el: '#simple',
data: {
clickedWord: '',
wordsList: ['word 1', 'word 2', 'word 3']
},
methods: {
cw_value: function() {
this.clickedWord = this.$refs.refWord.innerText
// "I don't know how to get inner text from a clicked value"
}
}
})
Share
Improve this question
edited May 26, 2017 at 20:45
thanksd
55.7k23 gold badges165 silver badges154 bronze badges
asked May 26, 2017 at 20:30
Marcin PanekMarcin Panek
351 silver badge7 bronze badges
2 Answers
Reset to default 6Since you've used ref="refWord"
on the same element as a v-for
, this.$refs.refWord
is an array containing each DOM element rendered by v-for
.
You should reference the index of each word, and then pass that to the click handler:
<li v-for="word, index in wordsList" @click="cw_value(index)" ref="refWord">
Then, in your cw_value
method, use the index value to access the correct element in the array:
cw_value: function(index) {
this.clickedWord = this.$refs.refWord[index].innerText;
}
Here's a working fiddle.
Alternatively, it would be much simpler to just set the clicked word inline in the click handler:
<li v-for="word in wordsList" @click="clickedWord = word">
Here's a working fiddle for that too.
Since innerText takes CSS styles into account, reading the value of innerText triggers a reflow to ensure up-to-date puted styles. (Reflows can be putationally expensive, and thus should be avoided when possible.) Here is MDN document on that.
Now it is:
this.$refs.refWord[index].textContent
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742301642a4418140.html
评论列表(0条)