Removing a Vue custom filter on mouseover

試著忘記壹切 提交于 2019-12-22 11:02:24

问题


I would like to remove a truncate filter on mouseover using VueJS 2. Here is my filter in the template:

<div class="eng" @mouseover="showAll">{{ word.english | truncate }}</div>

And here is the filter itself:

filters: {
    truncate: function(value) {
      let length = 50;
      if (value.length <= length) {
        return value;
      } else {
        return value.substring(0, length) + '...';
      }
    }
 },

Is there a way to remove the filter on the mouseover event so that the div is not truncated anymore? Thanks!

Edit: The showAll() function is where I thought I would remove it. I tried a couple ways to remove the filter such as:

showAll(){
  console.log('being mousedover');
  this.truncate = false
},

and:

showAll(){
  console.log('being mousedover');
  !this.truncate
}

but this is where I am lost...


回答1:


Make showAll a Boolean data property and use template tags to determine which version of word.english to display via the v-if and v-else directives:

<div class="eng" @mouseover="showAll = true">
  <template v-if="showAll">{{ word.english }}</template>
  <template v-else>{{ word.english | truncate }}</template>
</div>

Here's a working fiddle.




回答2:


The cleanest way to handle this is to set a boolean flag, and then filter a computed property based on the potential existence of the flag. This allows you to cache the value and you only need a single element with one conditional watcher instead of two.

HTML

<div class="eng" @mouseover="showAll = true" @mouseout="showAll = false">
  {{getWord}}
</div>

JS

export default {
    data() {
        return {
            showAll: false,
            word: {}
        }
    },
    computed: {
        getWord: function () {
            if (this.showAll) return this.word.english

            let value = this.word.english;
            let length = 50;
            if (value.length <= length) {
                return value;
            } else {
                return value.substring(0, length) + '...';
            }
        }
    }
}



回答3:


This should work.

data(){
    return {
      shouldTruncate: true
    }
},
methods: {
    showAll() {
        this.shouldTruncate = false
    }
},
filters:{
    truncate(value) {
        let length = 50;
        if (value.length <= length || !this.shouldTruncate) {
            return value;
        }
        else {
            return value.substring(0, length) + '...';
        }
    }
}


来源:https://stackoverflow.com/questions/45196501/removing-a-vue-custom-filter-on-mouseover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!