组件分为:
子传父
父传子
非父子之间的通信
1.子传父
用$emit(“事件”,参数)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>
<my-father></my-father>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component("my-father",{
template:`
<div>
<my-child @send='revMsg'></my-child>
<a href="#">{{mess}}</a>
</div>
`,
data:function(){
return{
mess:''
}
},
methods:{
revMsg:function(txt){
this.mess=txt
}
}
})
Vue.component("my-child",{
template:`
<button @click='sendMsg'>按钮</button>
`,
data:function(){
return{
msg:'我是子组件中的数据,要传给父组件'
}
},
methods:{
sendMsg:function(){
// this.$emit('事件',参数)
this.$emit('send',this.msg)
}
}
})
new Vue({
el:'#app'
})
</script>
</body>
</html>
2.父传子
用props 属性来传值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>
<my-father></my-father>
</div>
<script src='js/vue.js'></script>
<script>
Vue.component('my-father',{
template:`
<div>
<my-tit v-bind:tit='title'></my-tit>
<my-fruit v-bind:fruList='list'></my-fruit>
</div>
`,
data:function(){
return{
list:['apple','pear','banana'],
title:'水果列表'
}
}
})
Vue.component('my-tit',{
props:['tit'],
template:`
<h2>{{tit}}</h2>
`
})
Vue.component('my-fruit',{
props:['fruList'],
template:`
<ul>
<li v-for="value in fruList">{{value}}</li>
</ul>
`
})
new Vue({
el:'#app'
})
</script>
</body>
</html>
3.非父子之间传值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id='app'>
<child></child>
<son></son>
</div>
<script src='js/vue.js'></script>
<script>
var bus=new Vue();
Vue.component('child',{//a
template:`
<div>
<h2>我是child组件</h2>
<button @click='sendMsg'>发送数据</button>
</div>
`,
data:function(){
return{
msg:'我是child组件中的数据,要传给son组件'
}
},
methods:{
sendMsg:function(){//发送数据
bus.$emit('send',this.msg)
}
}
})
Vue.component('son',{//b
template:`
<div>
<h2>我是son组件</h2>
<a>{{mess}}</a>
</div>
`,
data:function(){
return{
mess:''
}
},
mounted:function(){
bus.$on('send',msg=>{
console.log(this);
this.mess=msg
})
}
})
new Vue({
el:'#app'
})
</script>
</body>
</html>