子向父組件傳值:
1,子組件中需要以某種方式例如點擊事件的方法來觸發(fā)一個自定義事件
2席怪,將需要傳的值作為$emit的第二個參數(shù),該值將作為實參傳給響應(yīng)自定義事件的方法
3茸习,在父組件中注冊子組件并在子組件標簽上綁定對自定義事件的監(jiān)聽
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../vue.min.js"></script>
</head>
<body>
<div id="app">
<v-child></v-child>
</div>
<template id="bbb">
<p>
<input v-model="ipt" />
<button @click="send()">發(fā)送</button>
{{info}}
</p>
</template>
<template id="aaa">
<p>
{{str}}
{{info}}
<v-childl :name='str' @jieshou="jieshousj"></v-childl>
</p>
</template>
<script>
var vm = new Vue({
el:'#app',
components:{
'v-child':{
template:'#aaa',
data:function(){
return {
info:"父組件",
str:''
}
},
methods:{
jieshousj:function(s){
this.str=s
}
},
components:{
'v-childl':{
template:'#bbb',
data:function(){
return {
info:'子組件',
ipt:''
}
},
methods:{
send(){
console.log(this.ipt)
this.$emit('jieshou',this.ipt)
}
}
}
}
}
}
})
</script>
</body>
</html>
父組件向子組件傳值:
1夜涕,子組件在props中創(chuàng)建一個屬性犯犁,用以接收父組件傳過來的值
2,父組件中注冊子組件
3女器,在子組件標簽中添加子組件props中創(chuàng)建的屬性
4酸役,把需要傳給子組件的值賦給該屬性
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../vue.min.js"></script>
</head>
<body>
<div id="app">
<v-child></v-child>
</div>
<template id="bbb">
<p>
{{name}}
{{info}}
</p>
</template>
<template id="aaa">
<p>
<input v-model="ipt" />
<button @click="send()">發(fā)送</button>
{{info}}
<v-childl :name='str'></v-childl>
</p>
</template>
<script>
var vm = new Vue({
el:'#app',
components:{
'v-child':{
template:'#aaa',
data:function(){
return {
info:"父組件",
str:'sss',
ipt:''
}
},
methods:{
send(){
this.str=this.ipt
}
},
components:{
'v-childl':{
template:'#bbb',
data:function(){
return {
info:'子組件'
}
},
props:['name']
}
}
}
}
})
</script>
</body>
</html>