在 vuejs 3 中截断单词(字符)

Truncate words (chars) in vuejs 3

如何在 VueJs 3 中截断单词或字符?我搜索了一些答案,但对我没有用。 例如,如果描述字的长度超过 200,则应显示 200 个字并...在末尾

到目前为止我尝试了什么..

<p>{{ announcement.description | truncate(200) }}</p>

<script>
export default {
data() {
    return {
      announcement: {},
    }
  },
computed:{
    truncate(value, length) {
        if (value.length > length) {
            return value.substring(0, length) + "...";
        } else {
            return value;
          }
    }
  }
}
</script>

您正在寻找的是一种方法,而不是计算 属性。 A computed property is used to declaratively describe a value that depends on other values。将您的代码移到方法中,并传递参数及其应该有效的长度。

    methods: {
       truncate(value, length) {
        if (value.length > length) {
            return value.substring(0, length) + "...";
        } else {
            return value;
          }
      }
   }

只需从模板中调用此方法即可:

truncate(announcement.description,200)

您可以从这里阅读有关 computed 的正确用法: https://vuejs.org/v2/guide/computed.html