Vue.js 中从 myInfo.js 获取特定 ID 的数据
<p>如果你在 'myinfo.vue' 的 '<script>' 中使用 'import name from '@/common/util/myInfo.js'' 导入 'myInfo.js' 文件,那么你可以按照以下方式获取 'id' 为 '1' 的 'name' 字段:</p>
<pre><code class="language-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>
</code></pre>
<p>在上述代码中,我们假设 'myInfo.js' 文件中导出的对象为 'myInfoData',且该对象包含一个名为 'data' 的数组。通过 'myInfoData.data' 可以访问到数组中的数据。我们使用 'Array.find' 方法查找 'id' 为 '1' 的数据对象,并将其 'name' 字段的值赋给 'targetName' 变量。在模板中使用 '{{ targetName }}' 显示该值。</p>
<p>请确保文件路径和对象名称与你的实际代码相匹配。</p>
<p>希望这个示例能够帮助到你,在 'myinfo.vue' 中获取 'id' 为 '1' 的 'name' 字段!</p>
原文地址: https://www.cveoy.top/t/topic/QIh 著作权归作者所有。请勿转载和采集!