先看一個demo
<body>
<div id="app">
<my_parent :parentimg="img" :parenttitle="title"></my_parent>
</div>
<template id="myimg">
<img :src="imgsrc">
</template>
<template id="mytitle">
<h2>{{childtitle}}</h2>
</template>
<template id="parent">
<div>
<child1 :imgsrc="parentimg"></child1>
<child2 :childtitle="parenttitle"></child2>
</div>
</template>
</body>
<script src="../js/vue.js"></script>
<script>
//創(chuàng)建子組件實例
let profile1 = Vue.extend({
template:"#myimg",
props: ["imgsrc"]
});
let profile2 = Vue.extend({
template:"#mytitle",
props:["childtitle"]
});
//注冊父組件
Vue.component("my_parent" , {
props: ["parentimg" , "parenttitle"],
components: {
"child1":profile1 ,
"child2":profile2
},
template:"#parent",
});
new Vue({
el:"#app",
data:{
title:"我是不是很美!",
img:"../img/img_02.jpg"
}
})
</script>
組件之間主要通過props進行值傳遞
上面demo中data中的img和title首先將值傳遞給父組件props的parentimg 和parenttitle,parentimg和parenttitle將值傳給imgsrc和childtitle,imgsrc和childtitle將值傳給子組件的src和<h2>{{}}</h2>