我是 VueJS 的新手,有一个理解问题,我找不到任何帮助。
非常简单:我通过带有 axios 的 API 获取 JSON。此项包含我要在页面上输出的描述。
我的代码看起来像这样:
<template>
<div v-for="item in listitems" :key="item.id">
{{ item.description }}
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import axios from 'axios'
export default defineComponent({
name: 'AllCoupons',
components: {
},
data: function() {
return {
listitems :[]
}
},
mounted: function() {
axios.get('https://api.com/endpoint',
{
headers: {
'Accept': 'application/json'
}
}).then((response) => {
console.log(response);
this.listitems = response.data.data
}).catch(error => {
console.log("ERRR:: ", error.response.data)
});
}
});
</script>
到目前为止一切正常。问题是 item.description 有太多字符,我想用 substr 之类的东西来限制。在 vue 中执行此类操作的正确/最佳方法是什么?
我想在方法中添加一个自定义函数,该函数将在 api 获取数据后运行,以遍历数据并进行修改,然后再将其传回 this.listitems。 - 但是有没有办法在模板中做这样的事情:?
{{ item.description.substring(1, 4); }}
我知道 Vue 2 和过滤器可以实现这样的事情,如果我是对的话......但是我怎么能在 Vue 3 中做这样的事情呢?
非常感谢!!
最佳答案
如 migration guide 中的建议,您可以使用计算属性,例如:
data: function() {
return {
listitems :[]
}
},
computed:{
customItems(){
return this.listitems.map(item=>{
return {...item, description:item.description.substring(1, 4)}
}
}
}
然后渲染计算属性:
<div v-for="item in customItems" :key="item.id">
{{ item.description }}
</div>
关于javascript - VueJS 3 - 模板/v-for 中的 substr/chop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64774276/