父組件向子組件傳值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app">
<!--父組件可以在引用子組件的時候 通過 屬性綁定的形式,把需要傳遞給子組件的數(shù)據(jù)以屬性綁定的形式,傳遞到子組件內(nèi)部 供
子組件使用-->
<com1 :parentmsg="msg"></com1>
</div>
</body>
<script>
var vm=new Vue({
el:"#app",
data:{
msg:"父組件中的數(shù)據(jù)"
},
components:{
com1:{
data:function(){//子組件中的data數(shù)據(jù)寇窑,并不是通過父組件傳遞過來的 而是子組件自身私有的,比如 子組件通過ajax
//請求回來的數(shù)據(jù)牛隅,都可以放到data身上
//data上的數(shù)據(jù)都是可讀可寫的
return {
title:"1",
content:"qqq"
}
},
methods:{
change(){
this.parentmsg='changge'
}
},
//經(jīng)過演示剂跟,發(fā)現(xiàn)子組件中,默認(rèn)無法訪問到父組件中的data上的數(shù)據(jù)和methods中的方法
template:"<h1 @click='change'>這是子組件 ---{{parentmsg}}</h1> ",
//把父組件傳遞過來的parentmsg屬性噩峦,先在props數(shù)組中 定義一下薪捍,這樣 才能使用這個數(shù)據(jù)
//組件中的props中的數(shù)據(jù)笼痹,都是通過父組件傳遞給子組件的
props:['parentmsg']
//props中的數(shù)據(jù)都是只讀的
}
}
})
</script>
</html>
使用的是PROPS來進(jìn)行傳值
子向父:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/vue.js"> </script>
</head>
<body>
<div id="app">
<!--父組件向子組件傳遞方法,使用的是事件綁定機(jī)制-->
<com2 v-on:abcac="show"></com2>
</div>
<template id="tmp1">
<div>
<input type="button" value="點擊" @click="myclick">
<h1>這是子組件</h1>
</div>
</template>
</body>
<script>
var com2={
template: "#tmp1",
data:function(){
return {
sonmsg:{age:6,name:"小頭兒子"}
}
},
methods:{
myclick(){
this.$emit('abcac',this.sonmsg)
}
}
}
var vm=new Vue({
el:"#app",
data:{
datamsgFromSon:null
},
methods:{
show(data){
//console.log('調(diào)用了父組件的show方法'+data)
console.log(data)
this.datamsgFromSon=data
}
},
components:{
com2:com2
}
})
</script>
</html>
$emit方法 第一個參數(shù)是函數(shù)名 第二個是要傳的值