之前我问过一个有关在Vue中删除自定义截断过滤器的问题。请在此处查看问题:

Removing a Vue custom filter on mouseover

但是,我忽略了提及我使用的是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>


并返回数据:

  data(){
    return {
      currentIndex: 0,
      roundClear: false,
      clickedWord: '',
      matchFirstTry: true,
      showAll: false,
    }
  },


如果您了解Vue,我将不胜感激。谢谢!

最佳答案

在您的示例中,v-for生成的每个按钮都使用showAll来确定是否显示word.english值的完整文本。这意味着只要触发任何mouseover类div的.eng事件,就会为每个按钮将相同的showAll属性设置为true。



我将showAll布尔值替换为最初设置为showWordIndexnull属性:

data() {
  showWordIndex: null,
},


然后在模板中,将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>


Here's a working fiddle.



更好的方法是制作一个新组件来封装v-for中呈现的所有内容的功能和模板,并将每个word对象的属性作为道具传递给子组件。

这样,您仍然可以像在示例中一样使用showAll属性,但是可以在子组件的作用域中对其进行定义。因此,现在showAll属性将仅影响与其相关的组件的实例。

下面是一个示例:



Vue.component('tile', {
  template: '#tile',
  props: ['pinyin', 'english'],
  data() {
    return { showAll: false };
  },
  filters: {
    truncate: function(value) {
      let length = 50;
      if (value.length <= length) {
        return value;
      } else {
        return value.substring(0, length) + '...';
      }
    }
  },
})

new Vue({
  el: '#app',
  data() {
    return {
      words: [
        {pinyin: 1, english: "really long string that will be cut off by the truncate function"},
        {pinyin: 2, english: "really long string that will be cut off by the truncate function"},
        {pinyin: 3, english: "really long string that will be cut off by the truncate function"},
        {pinyin: 4, english: "really long string that will be cut off by the truncate function"},
      ],
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.1/vue.min.js"></script>
<div id="app">
  <tile v-for="word, i in words" v-bind="word" :key="word"></tile>
</div>

<script id="tile" type="x-template">
  <button :title="english">
    <div class="pinyin">{{ pinyin }}</div>
    <div class="eng" @mouseover="showAll = true" @mouseout="showAll = false">
      <div v-if="showAll">{{ english }}</div>
      <div v-else>{{ english | truncate }}</div>
    </div>
  </button>
</script>

07-28 08:00