vue中父子组件传值问题

1.父组件向子组件传值–props

<template>
  <div>
    <hello-world :parentmsg="msg"></hello-world>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'home',
  components: {
    HelloWorld
  },
  data() {
    return {
      msg: '父组件传过来的值'
    }
  }
}
</script>
<template>
  <div class="hello">
   这是子组件--{{parentmsg}}
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  //props中的数据都是父组件传递给子组件的,只能读取,无法重新赋值
  props: ['parentmsg'] //父组件传递过来的parentmsg属性,先在props定义一下
}
</script>

2.父组件向子组件传递方法—$emit

<template>
  <div>
    <!-- 父组件向子组件传递方法使用的是事件绑定机制 -->
    <hello-world :parentmsg="msg" @func="show"></hello-world>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'home',
  components: {
    HelloWorld
  },
  methods: {
    show() {
      console.log('调用了父组件的方法')
    }
  },
}
</script>
<template>
  <div class="hello">
   <input type="button" value="这是父组件传递过来的方法" @click="myClick ">
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: ['parentmsg'],
  methods: {
    myClick() {
      this.$emit('func')
    }
  }
}
</script>

3.子组件向父组件传值 – 通过方法拿到子组件的值

<template>
  <div>
    <!-- 父组件向子组件传递方法使用的是事件绑定机制 -->
    <hello-world @func="show"></hello-world>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'home',
  components: {
    HelloWorld
  },
  data() {
    return {
      sonmsg: null
    }
  },
  methods: {
    show(data) {
      this.sonmsg = data
      console.log('调用了父组件的方法')
    }
  },
}
</script>

<template>
  <div class="hello">
   <input type="button" value="这是父组件传递过来的方法" @click="myClick  ">
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: ['parentmsg'],
  data() {
    return {
      params: {
        name: "cc",
        age: 18
      }
    }
  },
  methods: {
    myClick() {
      this.$emit('func', params)
    }
  }
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值