在Vue组件中动态显示来自外部JS文件的数据

本文将带你一步步实现如何在 myinfo.vue 组件中获取并显示来自 myInfo.js 文件中 id 为 '1' 的 name 字段。

1. 准备数据文件 (myInfo.js):

export const myInfoData = {
  data: [
    {
      id: '1',
      name: '孙凯',
      gender: '男'
    },
    {
      id: '2',
      name: '秀芹',
      gender: '女'
    }
  ]
};

2. 在Vue组件中导入数据并渲染 (myinfo.vue):

<template>
  <view class='my-headmsg'>
    <span>{{ targetName }}</span>
  </view>
</template>

<script>
import { myInfoData } from '@/common/util/myInfo.js';

export default {
  data() {
    return {
      targetName: ''
    };
  },
  mounted() {
    // 获取数据
    this.getData();
  },
  methods: {
    getData() {
      // 查找对应 id 的数据
      const targetData = myInfoData.data.find(item => item.id === '1');

      // 如果找到了目标数据,将目标数据的 name 字段赋值给 targetName
      if (targetData) {
        this.targetName = targetData.name;
      }
    }
  }
};
</script>

代码解释:

  • 导入数据: 使用 import 语句从 @/common/util/myInfo.js 文件中导入 myInfoData 对象。
  • 数据绑定: 在模板中使用 {{ targetName }}targetName 数据绑定到 <span> 标签内。
  • 生命周期钩子:mounted 生命周期钩子函数中调用 getData 方法,确保组件挂载后获取数据。
  • 查找数据: getData 方法使用 Array.find 方法查找 id 为 '1' 的数据对象。
  • 动态赋值: 如果找到了目标数据,则将目标数据的 name 属性赋值给 targetName 数据属性,从而动态更新模板中的内容。

通过以上步骤,你就可以在 myinfo.vue 组件中成功获取并显示来自外部 myInfo.js 文件的数据了!


原文地址: https://www.cveoy.top/t/topic/QHc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录