vue组件之间值传递几种方法汇总
1、父组件获取子组件的数据和方法 $refs
子组件:
<template>
<div class="header">
<h3>{{ zz }}</h3>
</div>
</template>
<script>
export default {
name: 'cx',
data () {
return {
zz: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
}
},
methods: {
zxx: function () {
alert('子组件方法zxx()')
}
}
}
</script>
<style scoped>
</style>
父组件:
<template>
<div>
<h1>{{ mm }}</h1>
<yyy ref="ry"></yyy>
</div>
</template>
<script>
import yyy from './cx'
export default {
name: 'cy',
data () {
return {
mm: 'YYYYYYYYYYYYYYYYYYYYYYYYYYYY'
}
},
mounted () {
alert(this.$refs.ry.zz)
this.$refs.ry.zxx('父组件赋值的值')
},
components: {
yyy: yyy
}
}
</script>
<style scoped>
</style>
传递对象:
props:{
z: {
type: Object
}
},
2、子组件调父组件的数据 props
子组件:
<template>
<div class="header">
<h3>{{ zz }}</h3>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'cx',
data () {
return {
zz: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
}
},
props: ['msg'],
methods: {
}
}
</script>
<style scoped>
</style>
父组件:
<template>
<div>
<h1>{{ mm }}</h1>
<yyy :msg = "fav"></yyy>
</div>
</template>
<script>
import yyy from './cx'
export default {
name: 'cy',
data () {
return {
mm: 'YYYYYYYYYYYYYYYYYYYYYYYYYYYY',
fav: '父组件的数据'
}
},
mounted () {
},
components: {
yyy: yyy
}
}
</script>
<style scoped>
</style>
3、子组件调用父组件的方法并传递数据 $emit
子组件:
<template>
<div class="header">
<h3>{{ zz }}</h3>
<button @click="cd">传递参数</button>
</div>
</template>
<script>
export default {
name: 'cx',
data () {
return {
zz: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
}
},
methods: {
cd: function (msg) {
this.$emit('zbt','子组件传递的参数')
}
}
}
</script>
<style scoped>
</style>
父组件:
<template>
<div>
<h1>{{ mm }}</h1>
<yyy type="button" @zbt = "bt">获取子组件传递的参数</yyy>
</div>
</template>
<script>
import yyy from './cx'
export default {
name: 'cy',
data () {
return {
mm: 'YYYYYYYYYYYYYYYYYYYYYYYYYYYY'
}
},
methods: {
bt: function (msg) {
alert(msg)
}
},
components: {
yyy: yyy
}
}
</script>
<style scoped>
</style>
4、兄弟组件互相传值 $emit $on
组件1
<template>
<div>
<h1>{{ mm }}</h1>
</div>
</template>
<script>
import Bus from '../bus.js'
export default {
name: 'cy',
data () {
return {
mm: 'YYYYYYYYYYYYYYYYYYYYYYYYYYYY'
}
},
mounted: function () {
Bus.$on('a',(xx) => {
alert('我是cy,获取到了cx的值:'+xx)
})
}
}
</script>
<style scoped>
</style>
组件2
<template>
<div class="header">
<h3>{{ zz }}</h3>
<!-- <el-button type="success" @click="bus">触发</el-button>-->
</div>
</template>
<script>
import Bus from '../bus.js'
export default {
name: 'cx',
data () {
return {
zz: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
}
},
mounted: function () {
var xx = "cx的值";
Bus.$emit('a',xx)
}
}
</script>
<style scoped>
</style>
Bus.js
import Vue from 'Vue' export default new Vue;
子组件调用父组件的方法:
方法1:
this.$parent.父组件方法();
如果父组件里子组件多套了一层,比如dialog:
this.$parent.$parent.父组件方法()
方法2:
this.$emit(‘父组件方法’);