Skip to content

Instantly share code, notes, and snippets.

@itzikbenh

itzikbenh/ReadMore.vue

Last active Sep 22, 2019
Embed
What would you like to do?
Vue Read More Component
<template>
<div v-if="text">
<div v-html="formattedText"></div>
<span v-if="text.length > maxChars">
<a href="#" v-if="!isReadMore" @click.prevent="triggerReadMore()">{{ readMoreText }}</a>
<a href="#" v-if="isReadMore && readLessText" @click.prevent="triggerReadLess()">{{ readLessText }}</a>
</span>
</div>
</template>
<script>
export default {
props: {
readMoreText: {
type: String,
default: "Read more"
},
readLessText: {
type: String,
default: "Read less"
},
text: {
type: String,
},
maxChars: {
type: Number,
default: 100
}
},
data() {
return {
isReadMore: false,
}
},
methods: {
triggerReadMore() {
this.isReadMore = true;
},
triggerReadLess() {
this.isReadMore = false;
}
},
computed: {
formattedText() {
let text = this.text;
if (! this.isReadMore && (this.text.length > this.maxChars)) {
text = `${ text.substr(0, text.lastIndexOf(' ', this.maxChars)) }...`;
}
return text;
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment