1.父向子 自定义属性
Vue组件间数据共享_BlackCarbo的博客-CSDN博客_vue 数据共享
2.子向父 自定义事件
<template>
<div class="son-container">
<h3>这是子组件 {{count}}</h3>
<button @click="add">+1</button>
</div>
</template>
<script>
export default {
data(){
return {
count:0
}
},
methods:{
add(){
this.count++
this.$emit('numChange',this.count)
},
}
}
</script>
<template>
<div id="app">
<h3>这是父组件--{{countFromSon}}</h3>
<Son @numChange="numChange1"></Son>
</div>
</template>
<script>
import Son from './components/Son.vue'
export default {
name: 'App',
components: {
Son
},
data(){
return {
countFromSon:0
}
},
methods : {
numChange1(val){
this.countFromSon = val
}
}
}
</script>
3.兄弟组件传递 eventbus
新建eventBus.js
import Vue from 'vue'
export default new Vue()
<template>
<div class="left-container">
<h3>这是left组件,将Left中属性分享到Right组件 {{count}}</h3>
<button @click="add">+1</button>
</div>
</template>
<script>
import bus from '../eventBus.js'
export default {
data(){
return {
count:0
}
},
methods:{
add(){
this.count++
bus.$emit('share',this.count)
}
}
}
</script>
<template>
<div class="right-container">
<h3>这是right组件 {{count}}</h3>
</div>
</template>
<script>
import bus from '../eventBus.js'
export default {
data(){
return {
count:0
}
},
created(){
bus.$on('share',val=>{
this.count = val
})
}
}
</script>