一、父組件調用子組件方法
父組件代碼 parent.vue
<template>
<div>
<button @click="parentFun">{{msg}}</button>
<child ref="child"></child>
</div>
</template>
<script>
import child from './child'
export default {
name: 'parent',
data () {
return {
msg: '我是父組件按鈕'
}
},
components: {
child,
},
methods:{
parentFun(){
this.$refs.child.childFun();
}
}
}
</script>
<style scoped>
</style>
子組件代碼 child.vue
<template>
<div>
我是子組件
</div>
</template>
<script>
export default {
name: 'child',
data () {
return {
msg: ''
}
},
methods:{
childFun(){
console.log('我是子組件方法')
},
}
}
</script>
<style scoped>
</style>
點擊“我是父組件按鈕” 會調用子組件 childFun() 方法
二、父組件向子組件傳參
父組件代碼 parent.vue
<template>
<div>
<child ref="child" :msg="msg"></child>
</div>
</template>
<script>
import child from './child'
export default {
name: 'parent',
data () {
return {
msg: '我是父組件按鈕參數'
}
},
components: {
child,
},
methods:{
}
}
</script>
<style scoped>
</style>
子組件代碼 child.vue
<template>
<div>
我是子組件
</div>
</template>
<script>
export default {
name: 'child',
props:{
msg:String
},
data () {
return {
}
},
methods:{
},
created(){
console.log(this.msg)
}
}
</script>
<style scoped>
</style>
把父組件要傳的參數綁定到子組件的標簽上,父組件用 props 接收參數,並注明參數類型,這樣子組件就會獲取到了
三、子組件向父組件傳值
父組件代碼 parent.vue
<template>
<div>
{{msg}}
<child @parentFun="getChildData" ></child>
</div>
</template>
<script>
import child from './child'
export default {
name: 'parent',
data () {
return {
msg: ''
}
},
components: {
child,
},
methods:{
getChildData(data){
this.msg = data;
}
}
}
</script>
<style scoped>
</style>
子組件代碼 child.vue
<template>
<div>
<button @click="sendParentMsg">我是子組件按鈕</button>
</div>
</template>
<script>
export default {
name: 'child',
data () {
return {
msg: '我是子組件的參數'
}
},
methods:{
sendParentMsg(){
//parentFun: 是父組件指定的傳數據綁定的函數,this.msg:子組件給父組件傳遞的數據
this.$emit('parentFun',this.msg)
},
}
}
</script>
<style scoped>
</style>
好了,常用的幾種父子組件之間的參數傳遞方法我整理了一些,希望對大家有所幫助
