Vue中的父子组件传值

1.父组件向子组件传值

        要在子组件中声明props进行接收

2.子组件向父组件传值

        在子组件中使用$emit()方法进行传值

代码示例:

        一、父组件代码

<template>
  <div class="app">
    <h2>我是父组件</h2>
    <p>子组件发送过来的值:{{num}}</p>
    <hr />
    <!-- 父组件传值 -->
    <FirstVue :msg="msg"></FirstVue>
    <hr />
    <!-- 接收子组件传过来的值 -->
    <!-- @方法名要和子组件$emit('方法名','要传的值')中的方法名一致 -->
    <SecendVue @sendnum="sendnum"></SecendVue>
  </div>
</template>

<script>
//引入两个子组件
import FirstVue from "@/components/FirstVue.vue";
import SecendVue from "./components/SecendVue.vue";
export default {
  name: "App",
  components: {
    FirstVue,
    SecendVue,
  },
  data() {
    return {
      msg: "我是父组件中的值",
      num:0
    };
  },
  methods: {
    sendnum(val){
      //val为子组件发送过来的参数
      this.num = val
    }
  },
};
</script>

<style></style>

二、子组件A(接收父组件的值)

<template>
    <div class="first">
        <h2>我第一个子组件</h2>
        <!-- 使用父组件传过来的值 -->
        <p>{{msg}}</p>
    </div>
</template>

<script>
export default {
    //接收父组件传过来的值
    props:["msg"],
    data () {
        return {}
    },
    methods: {},
}
</script>

<style lang="scss" scoped>
</style>

三、子组件B(向父组件传值)

<template>
  <div class="">
    <h2>我是第二个子组件</h2>
    <button @click="sendNum()">向父组件传值</button>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
    data () {
        return {
            num:20
        }
    },
    created () { },
    mounted () { },
    methods: {
        sendNum(){
            // 将num的值传给父组件
            this.$emit('sendnum',this.num)
        }
    },
    components: {}
}
</script>

<style lang="scss" scoped></style>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值