vue中的prop(父传子)
组件实例的作用域是孤立的。这意味着不能在子组件的模板内直接引用父组件的数据。父组件的数据需要通过prop才能下发到子组件中。
- (1.)props是子组件访问父组件数据的唯一接口。
- (2.)子组件用props来接收父组件传过来的值。
- (3.)子组件想使用父组件传来的值时,就在props中声明一个变量,之后变量就可引用父元素的数据。
(1.)prop的大小写
HTML中的大小写不是敏感的,浏览器会把所有大写的字符解释为小写字符,当使用DOM中的模板时驼峰命名写法的prop名需要使用等价的(短横线分割)命名
- 使用字符串模板则没有这个限制
- 例:
<componentA new-msg="hello!"></componentA>
<script>
Vue.component('componentA',{
props:[ 'newMsg'],
template: '<h3>{
{ newMsg }}</h3>'
})
</script>
(2.)prop类型
可以对象形式列出prop,属性的名称和值分别是prop各自名称和类型。
- 例:
props: {
title: String,
likes: Number,
isPublished: Boolean
}
(3.)传递静态或动态Prop
- (1.)prop传入静态值,例:
<div id="app">
// 父组件中子组件的标签设置一个自定义属性并赋值
<component-three value="my computer!!!"></component-three>
</div>
<template id="componentThree">
<h1>{
{
value}}</h1>
</template>
<script>
var ComponentC = {
data: