vue组件传值,方法调用

一.父组件向子组件传值

父组件

<template>
  <div class="parent">
    <!--在父组件加入子组件的地方    对父组件的数据进行绑定传输到子组件-->
    <!--     :自定义名称(子组件在props里面引用)=要传输的数据(对象)     -->
    <child :param1="msg" :param2="params"/>
  </div>
</template>

<script>
  import child from './child'
  export default {
    components: {child},
    name: 'parent',
    data() {
      return {
        msg: '我是父组件',
        params: {
          a: 1,
          b: "我是父组件集合"
        }
      }
    }
  }
</script>

子组件

<template>
  <div class="child">
    <p>{{param1}}</p>
    <p>{{param2}}</p>
  </div>
</template>

<script>
export default {
  name: 'child',
  props: {
    param1: {
      type:String,  //类型可以定义
      default:''  //默认是空值
    },
    param2: {
      type:Object,
      default () {
        return {
          // 可以为空,也可以自己定义
        }
      }
    }
  }
}
</script>

二.子组件向父组件传值

在子组件使用方法this.$emit('自定义的方法名','传父组件的值'),父组件使用v-on或者@绑定自定义的方法,然后触发父组件中的方法进行传值

父组件

<template>
  <div class="parent">
    <child @toParam1="parent1" @toParam2="parent2" />
    <p>{{msg}}</p>
    <p>{{params}}</p>
  </div>
</template>

<script>
  import child from './child'
  export default {
    components: {child},
    name: 'parent',
    data() {
      return {
        msg: '我是父组件',
        params: {
          a: 1,
          b: "我是父组件集合"
        }
      }
    },
    methods: {
      parent1 (param) {
        this.msg = param
      },
      parent2 (param) {
        this.params = param
      }
    }
  }
</script>

子组件

<template>
  <div class="child">
  </div>
</template>

<script>
export default {
  name: 'child',
  data () {
    return {
      msg: '我是子组件',
      params: {
        a: 1,
        b: "我是子组件集合"
      }
    }
  },
  created() {
    this.toParam()
  },
  methods: {
    toParam () {
      // 自定事件 $emit ==>this.$emit('自定义的方法,在父组件引用子组件的地方用','要传给父组件的值')
      this.$emit('toParam1',this.msg)
      this.$emit('toParam2',this.params)
    }
  }
}
</script>

三.父组件调用子组件的方法

父组件

<template>
  <div class="parent">
    <child ref="child"/>
    <button @click="pl">父组件按钮</button>
  </div>
</template>

<script>
  import child from './child'
  export default {
    components: {child},
    name: 'parent',
    data() {
      return {
        msg: '我是父组件',
        params: {
          a: 1,
          b: "我是父组件集合"
        }
      }
    },
    methods: {
      pl () {
        this.$refs.child.cl()
      }
    }
  }
</script>

子组件

<template>
  <div class="child">
  </div>
</template>

<script>
export default {
  name: 'child',
  methods: {
    cl () {
      console.log("我是子组件的方法")
    }
  }
}
</script>

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值