注释很详细,直接上代码
上一篇
新增内容
- 父组件传值
- 子组件接收父组件传来的数据
源码
App.vue
<template>
<div id="app">
<!-- :item="item"为将item的值传递给MyTest组件 -->
<MyTest v-for="item in roles" :key="item.id" :item="item" />
</div>
</template>
<script>
// 导入局部注册组件
import MyTest from "./components/MyTest.vue";
export default {
name: "App",
components: {
//注册局部注册组件
MyTest,
},
data() {
return {
//定义data值
roles: [
{ id: 0, name: "光头强", home: "小木屋", LoveToEat: "喜之郎果冻" },
{ id: 1, name: "熊二", home: "树洞", LoveToEat: "蜂蜜" },
{ id: 2, name: "吉吉国王", home: "山洞", LoveToEat: "香蕉" },
],
};
},
};
</script>
<style>
#app {
display: flex;
flex-direction: row;
}
</style>
MyTest.app
<template>
<div id="MyTest">
<div>名字:{{item.name}}</div>
<div>家:{{item.home}}</div>
<div>爱吃:{{item.LoveToEat}}</div>
</div>
</template>
<script>
export default {
// 因为组件每次使用都需要是一个新的对象,
// 所以data数据都需要是函数返回
data() {
return {
}
},
// 接收父组件传过来的数据
props:['item']
}
</script>
<style lang="less" scoped>
#MyTest{
box-sizing: border-box;
height:300px;
width:300px;
padding: 10px 0;
background-color: aquamarine;
margin: 10px;
border-radius: 10px;
display: flex;
flex-direction: column;
justify-content: space-around;
font-family: 华文彩云;
div{
text-align: center;
}
}
</style>
效果演示