Reputation: 1065
TLDR;
I have a Vue dropdown component that populates a list of selectable items.
<dropdown-component inline-template>
<div>
<!--Drop Label--><span v-on:click='showDropDown=!showDropDown' :class="{'active-menu': showDropDown, '': !showDropDown">{{someData.current.name1}} ({{someData.current.name2}}) {{someData.current.name3}}</span>
<!-- Drop Menu List --><div v-if='showDropDown' v-cloak v-model="showDropDown">
<div>
<input type="text" v-model="search" name="search" placeholder="Search" autocomplete="off">
</div>
<!-- Data populated list --><div v-for='data in searchFilter'>
<span v-on:click='dataClicked(data)'>{{data.name1}} {{data.name2}} {{data.name3}}</span>
</div>
</div>
</div>
</dropdown-component>
When an item is selected, the dropdown label is updated to the selected values.
for instance I have some data returned that is searchable:
data: function(){
return {
someData: someDataReturned.things, //only filtering array of things
search: ''
}
}
the structure of my data set is:
{
things: [{name1: value1, name2: value2},{name1: value1, name2: value2}],
current: {name1: value1, name2: value2, name3: value3}
}
Then with this data set I have a computed filter for a search to work
computed: {
searchFilter: function() {
var _this = this;
return this.someData.filter(function(obj){
return obj.name1.toString().indexOf(_this.search.toLowerCase()) >= 0;
});
}
The values can be different lengths and I'm trying to get a total count of all characters and truncate {{name1}} {{name2}} {{name3}}
accordingly.
when an item is selected, I set the current
values to update the label.
dataClicked: function(item) {
someData.current.name1 = item.name1;
someData.current.name2 = item.name2;
someData.current.name3 = item.name3;
}
HERE: ---
I'm wanting to get the total length of the label and truncate with filters
Something like:
filters: {
truncate: function(val){ return val.substring(0,30) }
}
Yet I only want to truncate name1
and name2
depending on the total length of the text combined. length of name1 + name2 + name3 , then truncate name1 and name2 accordingly.
Is there a way to do this in Vue with filters
?
Upvotes: 1
Views: 1049
Reputation: 29132
One way would be to pass the whole object to the filter.
In the template:
{{ someData.current | truncate }}
Then in your filters
:
truncate (current) {
var name1 = current.name1,
name2 = current.name2,
name3 = current.name3,
totalLength = name1.length + name2.length + name3.length;
if (totalLength > 30) {
// Inset appropriate truncation here
name1 = name1.slice(0, 4);
name2 = name2.slice(0, 4);
}
return name1 + ' ' + name2 + ' ' + name3;
}
As written here it will just truncate name1
and name2
to 4 characters. You haven't given any details of the truncation rules you're looking to apply so I haven't attempted anything more sophisticated.
Upvotes: 1