父子之间传值
父组件
<template>
<div class="p_div">
<span>父组件</span>
<input type="text" :value="sonFinfo">
<FirstSon :getP="p" @sendP="getSon1" />
</div>
</template>
<script>
import FirstSon from '@/components/FirstSon.vue'
export default {
name: 'parent',
data() {
return {
p: '父组件中的值',
sonFinfo: ''
}
},
components: {
FirstSon
},
methods: {
getSon1(val) {
this.sonFinfo = val
}
}
}
</script>
子组件1
<template>
<div class="son_div">
<span>子组件1</span>
<input type="text" :value="getP">
<button @click="send">send</button>
</div>
</template>
<script>
export default {
name: 'firstSon',
data() {
return {
son1: '子组件1中的值'
}
},
props: {
getP: String
},
methods: {
send() {
this.$emit('sendP', this.son1)
}
}
}
</script>
父传子
父组件将数据p发送给子组件
<FirstSon :getP="p" @sendP="getSon1" />
子组件通过定义props接收父组件传过来的值,定义了getP接收传进来的数据
props: {
getP: String
}
子传父
emit(arg1,arg2) arg1:方法名,arg2:要发送的值
子组件中按钮添加click事件触发send方法
<button @click="send">send</button>
methods: {
send() {
this.$emit('sendP', this.son1)
}
父组件中通过定义一个getSon1方法用来接收,该方法的的参数val就是子组件1发送过来的值
<FirstSon :getP="p" @sendP="getSon1" />
methods: {
getSon1(val) {
this.sonFinfo = val
}
兄弟间传值
创建一个Vue的实例,两子组件共用同一个事件机制
bus.js
import Vue from 'vue'
export default new Vue
父组件
<template>
<div class="p_div">
<FirstSon />
<SecondSon />
</div>
</template>
<script>
import FirstSon from '@/components/FirstSon.vue'
import SecondSon from '@/components/SecondSon.vue'
export default {
name: 'parent',
components: {
FirstSon,
SecondSon
}
}
</script>
子组件1
<template>
<div class="son_div">
<span>子组件1</span>
<button @click="send">send</button>
</div>
</template>
<script>
import bus from '@/bus/bus'
export default {
name: 'firstSon',
data() {
return {
son1: '子组件1中的值'
}
},
methods: {
send() {
bus.$emit('toSon2', this.son1)
}
}
}
</script>
子组件2
<template>
<div class="son_div">
<span>子组件2</span>
<input type="text" :value="son2">
</div>
</template>
<script>
import bus from '@/bus/bus'
export default {
name: 'secondSon',
data() {
return {
son2: ''
}
},
created() {
let t = this
bus.$on('toSon2', function(val) {
t.son2 = val
})
}
}
</script>
子组件分别导入bus.js
import bus from '@/bus/bus'
子组件1发送数据
通过一个事件触发bus.$emit(方法名,传递的数据)
methods: {
send() {
bus.$emit('toSon2', this.son1)
}
子组件2接收数据
bus.$on(方法名,function(接收的数据){})
created() {
let t = this
bus.$on('toSon2', function(val) {
t.son2 = val
})
}