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(‘父組件方法’);