vue(七)——组件传值

摘要

        vue的组件传值的方法有很多,今天复习的是父子组件之间的传值。至于vuex和事件总线,我们明天复习。

父组件传给子组件

        这个可以说是组件传值中最容易理解的。主要使用到组件中的props属性。

1、首先在父组件中引入并使用子组件

2、定义一个变量,并绑定到子组件中

3、在子组件的props中定义一个同名变量接收父组件传递的值

首先父组件

<template>
  <div class="home">
    <!-- home -->
    <!-- 使用子组件,并绑定msg传递给子组件 -->
    <hello-world :msg="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">
    <!-- 使用父组件传递的值 -->
    hello{{msg}}
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  // 接收父组件传递的值
  props: {
    msg: String
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">

</style>

效果:

子组件给父组件传值

        子组件给父组件传值是使用发送事件的方式,然后用事件参数来传递数据的。

1、首先子组件定义事件并发送给父组件

2、父组件定义变量用来保存子组件数据;并接收子组件事件

3、在父组件中处理子组件发送的事件,并保存传过来的数据

父组件:

<template>
  <div class="home">
    <!-- home -->
    {{msg1}}
    <!-- 使用子组件,并绑定msg传递给子组件 -->
    <hello-world :msg="msg" @aaa="hCli"></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:"父组件传给子组件的值",
      msg1:""
    }
  },
  methods: {
    hCli(value){
      this.msg1 = value;
    }
  },
}
</script>

子组件:

<template>
  <div class="hello">
    <!-- 使用父组件传递的值 -->
    hello{{msg}}
    <button @click="cli">点击发送事件</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  // 接收父组件传递的值
  props: {
    msg: String
  },
  data() {
    return {
      msg1:"子组件传递给父组件的值"
    }
  },
  methods: {
    cli(){
      this.$emit("aaa",this.msg1);
    }
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">

</style>

结果(未点击时)

 结果(点击后)

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

回首&逝去~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值