vue.js - vue中抓取数据时如何使用变量
问题描述
我正在尝试使我的方法动态化,我正在尝试将字符串传递给方法,然后该方法将相应地调整我的数据。
因此,当我传递海报的角色时,它应该传递给this.post.${user}.name
.
this.post.${user}.name
然后将“显示”为this.post.admin.name
然后获取管理员的姓名。
希望这是有道理的。
这是我的代码
<template>
<div>
<table class="table table-borderless table-striped">
<thead>
<tr>
<th>Posters</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ getName('admin') }}</td>
</tr>
<td>{{ getName('poster') }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props: ['post'],
data() {
return {
}
},
methods: {
getName(user){
if(this.post.${user}.name === null)
{
return "Unknown";
}else{
return this.post.${user}.name;
}
}
}
}
</script>
解决方案
对动态属性名称使用括号表示法:
export default {
methods: {
getName(user) {
if(!this.post[user]?.name) {
return "Unknown";
} else {
return this.post[user].name;
}
// OR:
return this.post[user]?.name ?? "Unknown";
}
}
}
推荐阅读
- python - 带有切片字符串的 Python 迭代器
- javascript - 为什么 setState 不更新我的状态值?
- google-cloud-platform - 将事务消息路由到无服务器实例
- html - 带有动态 div 的 span 上的 assertText
- python - 使用网状交叉引用 Rmarkdown 中的 python 代码块
- flutter - 如何在 Flutter 中使用 syncfusion_flutter_datepicker 仅获取 DateTime 格式的“日期”
- google-cloud-functions - 从不同项目的存储库中部署云函数时检索函数源代码失败
- configuration - gcloud init:从选择列表中删除旧用户
- reactjs - Pressable 和 TouchableWithoutFeedback 的区别
- javascript - 本地存储不会永久切换到夜间模式