vuejs 3 中截断单词(字符)

mir*_*dil 1 javascript vue.js vuejs3

如何在 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>
Run Code Online (Sandbox Code Playgroud)

Hum*_*far 7

您正在寻找的是方法,而不是计算属性。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;
          }
      }
   }
Run Code Online (Sandbox Code Playgroud)

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

truncate(announcement.description,200)

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