// main.js or your Vue.js entry file
import Vue from 'vue';
Vue.filter('str_limit', function (value, limit) {
if (!value) return '';
value = value.toString();
return value.length > limit ? value.substring(0, limit) + '...' : value;
});
<!-- Your Vue component template -->
<template>
<div>
{{ text | str_limit(20) }}
</div>
</template>
<script>
export default {
data() {
return {
text: "Your long text goes here."
};
}
};
</script>
- Import Vue in your main entry file (e.g.,
main.js
). - Define a Vue filter named 'str_limit' using
Vue.filter
. - The filter takes two parameters:
value
(the input string) and limit
(the maximum length of the output string). - Check if the input value is falsy, and return an empty string if true.
- Convert the input value to a string.
- If the length of the string is greater than the specified limit, use
substring
to truncate the string and append '...' at the end; otherwise, return the original string. - In your Vue component, use the filter in the template by piping the text through the 'str_limit' filter and passing the limit (e.g., 20) as an argument.
- The example component has a
text
data property with a long text value, which will be truncated using the 'str_limit' filter in the template.