Is there a way to apply a filter to the slot content in a Vue component?
To clarify, I would like to truncate the text included manually in the HTML. For example I would like to transform this:
<!-- In the view --> <my-component> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque, laboriosam quasi rerum obcaecati dignissimos autem laudantium error quas voluptatibus debitis? </my-component>
into this:
<!-- Generated component --> <div> Lorem ipsum dolor sit amet, consectetur adipisicing ... </div
I can't seem to find this information in the documentation.
Thank you.
v-slot is used on an HTML element. v-slot can only be used on a <template> element or the component receiving the slot. Otherwise, Vue throws a compile error. See Example 1 below. v-slot is used on a component, but the component has another <template v-slot> as a child.
When objects and arrays are passed as props, while the child component cannot mutate the prop binding, it will be able to mutate the object or array's nested properties. This is because in JavaScript objects and arrays are passed by reference, and it is unreasonably expensive for Vue to prevent such mutations.
Scoped slots are exactly like regular slots, with the difference that we pass data from the child component to the parent component. This data can then be used inside the slot content.
slotProps is just a variable we used to access the props we passed. You can also avoid setting a variable just to hold the props you pass to the child component, by destructuring the object on the fly: <page> <template v-slot="{ dogName }"> {{ dogName }} </template> </page>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With