一,在组件中定义并使用其他组件,就构成了父子组件的关系
步骤:1.注册并创建父组件
2.注册并创建子组件
父组件为全局组件
子组件为局部组件
那么最后的结果就是使用父组件,子组件也会被渲染
<div id="app">
<parent-component></parent-component>
</div>
<script>
//挂载
var vm=new Vue({
el:“#app”
})
//创建并注册父组件
Vue.component("parent-component",{
//在父组件中创建并注册子组件
component:{"child-component":{
template:“<p>this is a child commponent!</p>”
}}
template:"<p>this is a parent component!<child-component></child-component>"
})
</script>
上面代码最后运行的结果就是
this is a parent component
this is a child commponent!
ps:有两种错误写法,就是在使用组件的时候,父级标签里面套子级标签
或者将子级标签写在父级标签的下面。
二,props向子组件传递数据
1,组件实例的作用域是孤立的,这就代表着子组件的模板内不能够引用父组件的数据,但可以用props把数据传给子组件
2,一个组件可以有任意数量的props(属性),任何值都可以传递给任何props。
props的值可以是两种:一种是字符串数组,一种是对象
1,字符串数组
语法:
var component=Vue.extent({
props:[“属性名”,“属性名”,…],
template:“模板”
})
eg:
Vue.component(“blog-post”,{
props:["postTitle"],
template:"<h3>{{postTitle}}</h3>"
})
<blog-post post-title="hello!"></blog-post>
HTML中对属性名的大小写并不敏感,但在Vue里面写入的大驼峰命名法的属性名,到html页面的时候就需要使用短横线分隔符命名
2,props的值是对象
语法:
var component=Vue.extent({
props:{
属性名:String,
属性名:Numner,
属性名:Boolean,
…
},
template:“模板”
})