非父子组件通信-ref
案列:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<Father/>
</div>
<template id="father">
<div>
<h3>这里是father组件</h3>
<button @click = "printThis"> 输出this </button>
<hr>
<Girl :fn = "emitCry"></Girl>
<hr>
<Son ref = "son"></Son>
</div>
</template>
<template id = "son">
<div>
<h3> 这里是son组件 </h3>
<img v-if = "flag" style = "width: 100px;height: 100px;" src="https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1564471527&di=2c4707955cefb24c325842ea288b9647&src=http://b-ssl.duitang.com/uploads/item/201702/16/20170216145320_wyNiK.jpeg" alt="">
</div>
</template>
<template id="girl">
<div>
<h3> 这里是girl 组件 </h3>
<button @click = "fn"> 揍弟弟 </button>
</div>
</template>
</body>
<script src="../../person/vue.js"></script>
<script>
Vue.component('Father',{
template: '#father',
methods: {
printThis ( ) {
console.log( this )
},
emitCry () {
this.$refs.son.cry()
}
}
})
Vue.component('Son',{
template: '#son',
data () {
return {
flag: false
}
},
methods: {
cry () {
this.flag = true
}
}
})
Vue.component('Girl',{
template: '#girl',
props: ['fn']
})
new Vue({
el: '#app'
})
</script>
</html>
非父子通信-bus
案列:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<Girl></Girl>
<Son></Son>
</div>
<template id="girl">
<div>
<h3> 这里是girl </h3>
<button @click = "kick"> 揍弟弟 </button>
</div>
</template>
<template id="son">
<div>
<h3> 这里是son </h3>
<img style = "width: 100px;height: 100px;" v-if = "flag" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1564481613744&di=22ebae5b3c4655691a1244e46682d7c9&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201702%2F16%2F20170216145320_wyNiK.jpeg" alt="">
</div>
</template>
</body>
<script src="../../lib/vue.js"></script>
<script>
var bus = new Vue()
console.log( bus )
Vue.component('Son',{
template: '#son',
data () {
return {
flag: false
}
},
methods: {
cry () {
this.flag = true
}
},
mounted () { //这个选项表示组件挂载结束 这个方法时自定执行,只要组件创建,它就自动执行
// bus.$on(自定义事件的名称,自定义事件的处理程序)
var _this = this
bus.$on('aa',function () { // 通过$on自定义一个叫做aa的事件
_this.cry()
})
}
})
Vue.component('Girl',{
template: '#girl',
methods: {
kick () {
bus.$emit('aa')
}
}
})
new Vue({
el: '#app'
})
</script>
</html>