Vue - prop
prop作用#
prop的作用是父组件单向传递数据给子组件。
静态传递#
子组件
<tenplate>
<div>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
父组件
<template>
<div id="app">
<HelloWorld msg="hello world" />
</div>
</template>
<script>
export default {
name: "App",
components: {
HelloWorld,
},
};
</script>
动态传递字符串#
子组件
<tenplate>
<div>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
</script>
父组件
<template>
<div id="app">
<HelloWorld :msg="hello" />
</div>
</template>
<script>
export default {
name: "App",
components: {
HelloWorld,
},
data() {
return {
hello: "hello world",
};
},
};
</script>
动态传递数组#
子组件
<template>
<div class="hello">
<ul>
<li v-for="item in hellos" :key="item">{{ item }}</li>
</ul>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
hellos: String,
msg: String
},
};
</script>
父组件
<template>
<div id="app">
<HelloWorld :msg="hello" :hellos="hellos" />
</div>
</template>
export default {
name: "App",
components: {
HelloWorld,
},
data() {
return {
hello: "hello world",
hellos: ["111", "222", "333"],
};
},
};
</script>
动态传递对象#
子组件
<template>
<div class="hello">
<h1>{{ msg.id }}</h1>
<h2>{{ msg.name }}</h2>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: Object,
},
};
</script>
父组件
<template>
<div id="app">
<HelloWorld :msg="hello"/>
</div>
</template>
<script>
export default {
name: "App",
components: {
HelloWorld,
},
data() {
return {
hello: {
id: 1,
name: "wecle",
},
};
},
};
</script>
prop验证#
type可以是:
String
Number
Boolean
Array
Object
Date
Funtion
Symbol
子组件
<template>
<div class="hello">
<h1>{{ string }}</h1>
<h1>{{ number }}</h1>
<h1>{{ boolean }}</h1>
<h1>{{ array }}</h1>
<h1>{{ object }}</h1>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
string: {
type: String,
},
number: {
type: Number,
},
boolean: {
type: Boolean,
},
array: {
type: Array,
},
object: {
type: Object,
},
},
};
</script>
父组件
<template>
<div id="app">
<HelloWorld
:string="string"
:number="number"
:boolean="boolean"
:array="array"
:object="object"
/>
</div>
</template>
<script>
export default {
name: "App",
components: {
HelloWorld,
},
data() {
return {
string: "验证字符串",
number: 123456,
boolean: true,
array: ["这是", "一个", "数组"],
object: {
id: 1,
name: "验证对象",
},
};
},
};
</script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~