lna*_*mba 2 javascript vue.js vuejs2
之前我问过一个关于在 Vue 中删除自定义 truncate 过滤器的问题。请看这里的问题:
但是,我忽略了我正在使用 v-for 循环,当我将鼠标悬停在一个 div 上时,我注意到循环中的所有 div 都对它们应用了相同的操作。我不确定如何只定位悬停在上面的 div。这是我的模板:
<div id="tiles">
<button class="tile" v-for="(word, index) in shuffled" @click="clickWord(word, index)" :title="word.english">
<div class="pinyin">{{ word.pinyin }}</div>
<div class="eng" @mouseover="showAll = true" @mouseout="showAll = false">
<div v-if="showAll">{{ word.english }}</div>
<div v-else>{{ word.english | truncate }}</div>
</div>
</button>
</div>
Run Code Online (Sandbox Code Playgroud)
和返回的数据:
data(){
return {
currentIndex: 0,
roundClear: false,
clickedWord: '',
matchFirstTry: true,
showAll: false,
}
},
Run Code Online (Sandbox Code Playgroud)
如果您了解 Vue,我将不胜感激。谢谢!
在您的示例中,showAll用于 v-for 生成的每个按钮来确定是否显示word.english值的完整文本。这意味着每当mouseover任何.eng类 div的事件触发时,showAll每个按钮的相同属性都会设置为 true。
我会用最初设置为showAll的showWordIndex属性替换布尔值null:
data() {
showWordIndex: null,
},
Run Code Online (Sandbox Code Playgroud)
然后在模板中,设置showWordIndex为index这个词对mouseover处理器(以及null在mouseleave处理):
<button v-for="(word, index) in shuffled" :key="index">
<div class="pinyin">{{ word.pinyin }}</div>
<div
class="eng"
@mouseover="showWordIndex = index"
@mouseout="showWordIndex = null"
>
<div v-if="showWordIndex === index">{{ word.english }}</div>
<div v-else>{{ word.english | truncate }}</div>
</div>
</button>
Run Code Online (Sandbox Code Playgroud)
更好的是制作一个新组件来封装在 中呈现的所有内容的功能和模板v-for,将每个word对象的属性作为道具传递给子组件。
这样,您仍然可以showAll像在示例中一样使用该属性,但您将在子组件的范围内定义它。所以现在这个showAll属性只会影响它相关的组件的实例。
下面是一个例子:
data() {
showWordIndex: null,
},
Run Code Online (Sandbox Code Playgroud)
<button v-for="(word, index) in shuffled" :key="index">
<div class="pinyin">{{ word.pinyin }}</div>
<div
class="eng"
@mouseover="showWordIndex = index"
@mouseout="showWordIndex = null"
>
<div v-if="showWordIndex === index">{{ word.english }}</div>
<div v-else>{{ word.english | truncate }}</div>
</div>
</button>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1506 次 |
| 最近记录: |