创建一个自定义组件:
<template>
<h1>Here is ComponentForOne!!</h1>
<p>{{title}}</p>
<p>age = {{age}}</p>
<ul style="background-color:aqua">
<li v-for="(item,index) in arr" :key="index">{{item}}</li>
</ul>
</template>
<script>
// 导出
export default{
// 当前组件的名称,在导入使用时需要用到
name:"ComponentForOne",
// 通过props在组件间传递参数
props:{
title:{
type:String,
default:""
},
age:{
type:Number,
default:20
},
arr:{
type:Array,
// 数组和对象必须使用函数返回
default:function(){
return []
}
}
}
}
</script>
<!-- scoped :如果添加了此属性,表示只在当前组件中生效 -->
<style scoped>
h1{
color: aqua;
}
</style>
在App.vu中引入:
<template>
<img alt="Vue logo" src="./assets/logo.png">
<!-- 下面使用组件:组件标签名 -->
<ComponentForOne :title="msg" :age="age" :arr="arr"/>
</template>
<script>
// 此处引入组件 import 组件标签名 from 组件所在位置
import ComponentForOne from './components/ComponentForOne.vue';
export default {
name: 'App',
components: {
// 挂载组件
ComponentForOne
},
data(){
return{
msg:"App中的msg",
age:12,
arr:["1","2","3"]
}
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
在App.vue中通过将值绑定在属性上进行传递,在自定义组件中通过 props 进行接收然后设置到标签中。
对应关系:
App.vue中的 data 中设置值,App.vue 的自定义组件标签中设置属性,并将值设置为属性值,
自定义组件中的 props 引入App.vue 中设置的值,然后设置到标签中。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)