javascript - 如何将数据传递给子组件并在子组件中呈现?
问题描述
我正在尝试将数组从父级传递给子级,但在子级而不是父级中渲染/输出它。在我发现的教程中,我只能在父级中渲染数组。例如,我有以下内容:
孩子
<template>
<div>
{{tile.name}} {{formattedPoints}}
</div>
</template>
<script>
export default {
props: {
tile: {
required: true,
type: Object
}
},
computed: {
formattedPoints() {
return this.tile[0].name = 5
}
}
}
</script>
父母
<template>
<div>
<User v-for="tile in tileMenu" :key="tile.id" :tile="tile" />
</div>
</template>
<script>
import User from './Home.vue'
import { ref } from 'vue'
export default {
components: {
User
},
setup() {
const tileMenu = ref([
{ id: 1, name: 'tile1' },
{ id: 2, name: 'tile2' },
])
return { tileMenu }
}
}
</script>
在这个例子中,我将与父母一起制作输出,但我喜欢与孩子一起制作。在我的思考过程中,这应该是可能的,因为我将数组传递给子组件,如果我这样称呼它
<template>
<div>
{{tile[0].name}}
</div>
</template>
它应该给我子组件的输出。但这什么也没输出。我该如何解决这个问题?提前致谢
解决方案
我可以建议你(并且 id 需要是唯一的,因为它是你在 for 循环中的关键)
家长:
<template>
<div>
<User :tileMenu="tileMenu" /> <!--pass all array-->
</div>
</template>
<script>
import User from "./Home.vue";
const tileMenu = [
{ id: 1, name: "tile1NAME" },
{ id: 2, name: "tile2NAME" },
];
export default {
components: {
User,
},
data() {
return {
tileMenu: tileMenu,
};
},
};
</script>
孩子:
<template>
<div>
<div v-for="tile in tileMenuChild" :key="tile.id">
{{ tile.name }} with id {{ tile.id }}
</div>
</div>
</template>
<script>
export default {
props: {
tileMenu: Array,
},
data() {
return {
tileMenuChild: this.tileMenu,
};
},
};
</script>
推荐阅读
- c++ - C++ long double 更大的“安全”整数
- swift - PromiseKit 在 Promises 中包装外部闭包
- postgresql - 有一个没有间隙的序数列
- python - Pathlib Path.rename() 创建中间目录的方式?
- javascript - 在 javascript ES6 中寻找更高效的排序算法
- python-3.x - Python为类的字典理解定义迭代器
- html - html固定导航栏
- assembly - 多字指令的影响
- java - 测试结果中未考虑 JMeter 作为代码断言
- python-3.x - PuLP: TypeError: Can only add LpConstraintVar, LpConstraint, LpAffineExpression or True objects