1.子组件
defineProps
<template>
<view class="userinfo">
<image :src="avatar" mode="aspectFill" class="avatar"></image>
<view class="username">{{username}}</view>
</view>
</template>
defineProps(['username', 'avatar'])
2.父组件
传参
<UserInfo username='niao' avatar="../../static/pic1.jpg"></UserInfo>
<UserInfo username='zhangsan' avatar="../../static/pic2.jpg"></UserInfo>
<UserInfo username='lisi' avatar="../../static/pic3.jpg"></UserInfo>
注意:
1.如果要在后端显示从父组件拿来的数据 用props接收
const name = computed(() => props.username + "~~")
2.props 校验
const props = defineProps({
username: {
type: String,
default: "匿名"
},
avatar: {
type: String,
default: '../../static/logo.png'
}
})
3.父传子之间
父组件
<template>
<view class="content">
<UserInfo v-for="(item,index) in userinfo" :obj="item"></UserInfo>
</view>
</template>
<script setup>
import {
ref
} from "vue";
const userinfo = ref([{
name: "张三",
avatar: "../../static/pic1.jpg"
},
{
name: "李四",
avatar: "../../static/pic2.jpg"
},
{
name: "王五",
avatar: "../../static/pic3.jpg"
},
])
</script>
<style>
</style>
子组件
<template>
<view class="userinfo">
<image :src="obj.avatar" mode=""></image>
<view class="username">{{obj.name}}</view>
</view>
</template>
<script setup>
import {
computed
} from "vue"
const props = defineProps({
obj: {
type: Object,
default () {
return {
name: '匿名',
avatar: '../../static/logo.png'
}
}
}
})
</script>
<style lang="scss" scoped>
.userinfo {
width: 100%;
height: 200px;
background: #ccc;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
image {
width: 100px;
height: 100px;
border-radius: 50%;
}
.username {
padding: 10px 0;
font-size: 20px;
}
}
</style>