概述
在父组件与子组件中,为了实现父子组件之间的通信,需要使用props,来实现父组件中的内容被子组件所使用。在子组件中使用props来进行与父组件之间的通信。
在使用组件时通过绑定props中定义的变量与父组件中的属性,实现父组件的属性传递到子组件,子组件就可以使用父组件的属性了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>父传子组件props</title>
</head>
<body>
<div id="app">
<cpn :c-foods="foods" :c-message="message"></cpn>
</div>
<template id="cpn">
<div>
<ul>
<li v-for="item in cFoods">{{item}}</li>
</ul>
<h2>{{cMessage}}</h2>
</div>
</template>
<script src="js/vue.js"></script>
<script>
const cpn = {
template: '#cpn',
props: {
'cFoods': {},
'cMessage': {}
},
data() {
return {};
}
}
const app = new Vue({
el: '#app',
data: {
foods: ['回锅肉', '糖醋里脊', '鱼香肉丝', '糖醋鲤鱼'],
message: '欢迎来到本系统'
},
components: {
cpn
}
})
</script>
</body>
</html>
对于props来说,可以对其进行类型限制、提供默认值
类型限制
props: {
'cFoods': Array,
'cMessage': String
}
提供默认值
'cMessage': {
type: String,
default: '1234567'
}
必须传值
'cMessage': {
type: String,
default: '1234567',
required: true
}
类型为对象或数组
当类型为对象(Object)或者数组(Array)时,默认值必须为函数,否则会报错
'cMessage': {
type: Array,
default() {}
}
当props中的变量使用驼峰命名法时,在调用组件时,若使用驼峰命名法进行绑定时,系统不会识别,所以在调用组件时,绑定时使用“-”。
<div id="app">
<cpn :c-foods="foods" :c-message="message"></cpn>
</div>
props: {
'cFoods': Array,
'cMessage': {
type: Array,
default() {}
}
最后
以上就是美满超短裙为你收集整理的父子组件通信——父传子props的全部内容,希望文章能够帮你解决父子组件通信——父传子props所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复