首页 > 解决方案 > 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>

标签: vue.js

解决方案


对动态属性名称使用括号表示法:

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";
    }
  }
}

推荐阅读