2017-05-26 430 views
1

我想获取呈现列表中的项目的innerText,但使用this.$refs访问它似乎不起作用。我也尝试使用v-modal,这似乎也没有工作。如何获取VueJS中呈现的列表项的innerText

这里是我的代码:

<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" 
    } 
    } 
}) 

回答

1

既然你已经使用ref="refWord"在相同的元素为v-forthis.$refs.refWord是包含v-for渲染的每一个DOM元素的数组。

你应该引用每个字的索引,然后传递到单击处理程序:

<li v-for="word, index in wordsList" @click="cw_value(index)" ref="refWord"> 

然后,在你cw_value方法,使用索引值来访问正确的元素数组中:

cw_value: function(index) { 
    this.clickedWord = this.$refs.refWord[index].innerText; 
} 

Here's a working fiddle.


Altern atively,它就会简单得多,只是设置点击的话内嵌单击处理程序:

<li v-for="word in wordsList" @click="clickedWord = word"> 

Here's a working fiddle for that too.

+0

你是个天才。谢谢 –