我有一个使用 VueX 的 Vue Js 应用程序。在我的一个组件中,我正在调用一种方法来截断一些文本。此 truncate 方法位于用于小型辅助函数的单独文件中。我试图截断的那段文本是从从数据库中提取的状态中提取的。
假设这是我状态下的用户对象:
userState: {
name: "John Doe",
bio: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsum laborum amet, dolores molestiae voluptates ea animi fugit quo repudiandae facilis.",
age: 35
}
在我的模板中,我这样称呼 bio:
<p>{{ truncate(userState.bio, 20, "...") }}</p>
在我的组件方法中,我有以下方法:
const helpers = require("@/utilities/helpers");
methods: {
truncate(text, length, ending) {
return helpers.truncateText(text, length, ending);
}
}
我的助手文件中的方法是:
export const truncateText = (str, length, ending) => {
if (length == null) {
length = 100;
}
if (ending == null) {
ending = '...';
}
if (str.length > length) {
return str.substring(0, length - ending.length) + ending;
} else {
return str;
}
}
我得到的消息是:
TypeError: Cannot read property 'length' of undefined
但奇怪的是,截断的文本在 dom 中呈现......即使控制台中出现错误。
任何想法这里发生了什么?
提前致谢!!
编辑:
我应该提到在user,bio
没有 truncate 方法的情况下调用我完全没有错误并且 bio 呈现正常。
很可能是初始状态userState.bio
为undefined,错误来自于初始渲染时数据未更新;尝试在您的条件中添加另一个字符串检查以消除错误:
if (str && str.length > length) {
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句