vue.js components : How to truncate the text in the slot element in a component?

The same thing on similar way can be:

in your main.js file:

var filter = function(text, length, clamp){
    clamp = clamp || '...';
    var node = document.createElement('div');
    node.innerHTML = text;
    var content = node.textContent;
    return content.length > length ? content.slice(0, length) + clamp : content;
};

Vue.filter('truncate', filter);

in your template:

{{data.content | truncate(300, '...')}}

You can use a filter to truncate it.

//credit to @Bill Criswell for this filter
Vue.filter('truncate', function (text, stop, clamp) {
    return text.slice(0, stop) + (stop < text.length ? clamp || '...' : '')
})

Then give the filter the length you want the string to be

<my-component>
    {{'Lorem ipsum dolor sit amet, consectetur adipisicing' | truncate 50 }}
</my-component>

Within the child component, content from a slot is passed through as-is, and isn't available as a variable that you could truncate from the child end.

Tags:

Vue.Js