一、父传子
关键词:添加属性 props
<body>
<div id="edd">
<v-fa></v-fa>
<v-box> </v-box>
</div>
<template id="father">
<div>
<p>{{str}}</p>
<button @click='tap'>向子组件传值</button>
<hr/>
<v-child :name='str1'></v-child>
</div>
</template>
<template id="child">
<div>
<p>{{this.name}}</p>
</div>
</template>
</body>
<script>
var vm = new Vue({
el:'#edd',
components:{
'v-fa':{
template:'#father',
data:function(){
return {
str:'我是父组件',
str1:''
}
},
methods:{
tap(){
this.str1=this.str
}
},
components:{
'v-child':{
props:['name'],
template:'#child',
data:function(){
return{}
}
}
}
},
}
})
</script>
二、子传父
关键词:$emit 定义方法
<body>
<div id="out">
<v-father></v-father>
</div>
<template id="father">
<div>
<h1>father------{{str}}</h1>
<hr>
<v-child @to-parent="getdata"></v-child>
</div>
</template>
<template id="child">
<div>
<h1>childr-------{{str}}</h1>
</div>
</template>
</body>
<script>
var vm = new Vue({
el:'#out',
components:{
'v-father':{
template:'#father',
data(){
return{
str:''
}
},
methods:{
getdata(msg){
this.str = msg
}
},
components:{
'v-child':{
template:'#child',
data(){
return{
str:'this is child'
}
},
created(){
this.$emit('to-parent',this.str)
}
}
}
}
}
})
</script>
三、平行组件传值
关键词:$emit $on 空的vue对象
<body>
<div id="app">
<v-a></v-a>
<hr>
<v-b></v-b>
</div>
<template id="a">
<div>
this is a {{str}}
<button @click='tap'>send</button>
</div>
</template>
<template id="b">
<div>
this is b {{str}}
</div>
</template>
</body>
<script>
var vm1 = new Vue()
var vm = new Vue({
el:'#app',
components:{
'v-a':{
template:'#a',
data(){
return {
str:'this is a ,need to b'
}
},
methods:{
tap(){
vm1.$emit("isa",this.str)
}
}
},
'v-b':{
template:'#b',
data(){
return{
str:''
}
},
mounted(){
var _this = this;
vm1.$on("isa",function(msg){
_this.str = msg
})
}
}
}
})
</script>