Removing a custom Vue filter on hover
I would like to remove the truncate on mouseover filter using VueJS 2. Here is my filter in the template:
<div class="eng" @mouseover="showAll">{{ word.english | truncate }}</div>
And here's 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 no longer truncated? Thank!
Edit: The function showAll()
is where I thought I would remove it. I tried a couple of ways to remove the filter, for example:
showAll(){
console.log('being mousedover');
this.truncate = false
},
and
showAll(){
console.log('being mousedover');
!this.truncate
}
but this is where i got lost ...
source to share
Make showAll
a Boolean data property and use tags template
to define which version to word.english
display using directives v-if
and v-else
:
<div class="eng" @mouseover="showAll = true">
<template v-if="showAll">{{ word.english }}</template>
<template v-else>{{ word.english | truncate }}</template>
</div>
source to share
The cleanest way to deal with this is to set a boolean flag and then filter the computed property based on the flag's potential existence. This allows you to cache the value and you only need one element with one conditional observer 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) + '...';
}
}
}
}
source to share
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) + '...';
}
}
}
source to share