1、父传子
父组件
<template>
<div class="hello">
<Son :message="sons" ></Son><!-- @btn="btn"-->
</div>
</template>
<script>
import Son from './son'
export default {
components:{
Son
},
data () {
return {
sons:'我是儿子'
}
},
methods:{
}
}
</script>
子组件
<template>
<div>
{{message}}
</div>
</template>
<script>
export default{
props: {
message:{
type:String,
default:''
}
},
data () {
return {
}
},
methods:{
}
}
</script>
2、子传父
父组件
<template>
<div class="hello">
<Son @father="getFromSon"></Son>
</div>
</template>
<script>
import Son from './son'
export default {
components:{
Son
},
data () {
return {
getSon:''
}
},
methods:{
getFromSon(msg){//子传过来的数据
this.getSon=msg;
}
}
}
</script>
子组件
<template>
<div @click="toFather">
传到父组件
</div>
</template>
<script>
export default{
data () {
return {
father:'我是父亲'
}
},
methods:{
toFather(){//给父传参
this.$emit('father',this.father);
}
}
}
</script>
3、子调用父方法
父组件
<template>
<div class="hello">
<Son :message="sons" @btn="btn" ></Son><!-- $emit方法,需要将方法像参数一样传递给子组件-->
<Son :message="sons" :btn="btn" ></Son><!-- 直接调用方法,需要将方法像参数一样传递给子组件-->
<Son ></Son><!-- $parent方法-->
</div>
</template>
<script>
import Son from './son'
export default {
components:{
Son
},
data () {
return {
sons:'我是儿子'
}
},
methods:{
btn(){
this.sons='我是孙子aaa'
}
}
}
</script>
子组件
<template>
<div>
<div @click="getFather()">无可奈何花落去要</div>
</div>
</template>
<script>
export default{
props: {
btn: {//$emit 、直接调用 两方法来调用父组件方法,需要先将方法注入到子组件中
type: Function,
default: null
}
},
data () {
return {
}
},
methods:{
getFather(){//调用父方法
this.$emit('btn')//$emit方法来调用父组件方法
this.$parent.btn();//$parent方法来调用父组件方法
this.btn()//直接调用 方法
}
}
}
</script>
4、父调用子方法
父组件
<template>
<div class="hello">
<Son ref="son"></Son>
</div>
</template>
<script>
import Son from './son'
export default {
components:{
Son
},
data () {
return {
sons:'我是儿子'
}
},
methods:{
getSonMethods(){//调用子的方法
this.$refs.son.toF()
}
}
}
</script>
子组件
<template>
<div>
<div>{{num}}</div>
</div>
</div>
</template>
<script>
export default{
data () {
return {
num:1
}
},
methods:{
toF(){
this.num*=10;
}
}
}
</script>
以上就是个人遇到的传参问题,如有不足请指证