组件实例的作用域是孤立的。这意味着不能并且不应该在子组件的模板内直接引用父组件的数据。可以使用 props 把数据传给子组件。
“prop” 是组件数据的一个字段,期望从父组件传下来。子组件需要显式地用 props 选项 声明 props:
Vue.component('child', {
// 声明 props
props: ['msg'],
// prop 可以用在模板内
// 可以用 `this.msg` 设置
template: '<span>{{ msg }}</span>'
})
然后向它传入一个普通字符串:
<child msg="hello!"></child>
实例:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="bower_components/vue/dist/vue.js"></script>
</head>
<body>
<div id="box">
<aaa></aaa>
</div>
<template id="aaa">
<bbb mmm="hello"></bbb>
</template>
<script>
var vm=new Vue({
el:"#box",
data:{
a:"aaa"
},
components:{
"aaa":{
data(){
return {
msg2:"我是父组件的数据"
}
},
template:"#aaa",
components:{
"bbb":{
props:["mmm"],
template:"<h3>我是bbb的组件->{{mmm}}</h3>"
}
}
}
}
})
</script>
</body>
</html>
camelCase vs. kebab-case
HTML 特性不区分大小写。名字形式为 camelCase 的 prop 用作特性时,需要转为 kebab-case(短横线隔开):
Vue.component('child', {
// camelCase in JavaScript
props: ['myMessage'],
template: '<span>{{ myMessage }}</span>'
})
<!-- kebab-case in HTML -->
<child my-message="hello!"></child>
类似于用 v-bind 绑定 HTML 特性到一个表达式,也可以用 v-bind 绑定动态 Props 到父组件的数据。每当父组件的数据变化时,也会传导给子组件:
实例:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="bower_components/vue/dist/vue.js"></script>
</head>
<body>
<div id="box">
<aaa></aaa>
</div>
<template id="aaa">
<bbb :mmm="msg2"></bbb>
</template>
<script>
var vm=new Vue({
el:"#box",
data:{
a:"aaa"
},
components:{
"aaa":{
data(){
return {
msg2:"我是父组件的数据"
}
},
template:"#aaa",
components:{
"bbb":{
props:["mmm"],
template:"<h3>我是bbb的组件->{{mmm}}</h3>"
}
}
}
}
})
</script>
</body>
</html>