vue父子组件传值

一个理想的 Vue 应用是 prop 向下传递,事件向上传递的。


父组件向子组件传值

子组件定义 props: ['data'] 数据

子组件使用时添加相同名称的属性  data="son-one"

父组件直接拿取子组件的值或调用子组件方法

给相应的子组件标签上加 ref属性,直接调用即可

子组件向父组件传值

方法一

this.$emit方法

如果子组件想要给父组件传入多个值

子组件写多个参数,父组件获取多个参数的值

方法二

父组件给子组件传递一个带参函数 

<MyHeader :addTodo="addTodo"/>

addTodo(todoObj){

        console.log(todoObj)

},

子组件向函数里传值

props:['addTodo'],

add(){

        this.addTodo(todoObj)

}

父组件

<template>
  <div>
    <div style="margin: 1.25rem;">
      普通方式:<br />
      <son-one @childFn="parentFn" data="son-one"></son-one>
      <br />
      子组件传来的值 : {{message}}
    </div>
    <div style="margin: 1.25rem;">
      component:<br />
      <component :is="currentView" @childFn="parentFn" :data="sendSon"></component>
      <br />
      子组件传来的值 : {{message}}
    </div>
    <div style="margin: 1.25rem;">
      ref:<br />
       <!-- @childFn="parentFn" 没有加这个标签,子组件的值就传不过来 -->
      <component ref="ch" :is="currentView" :data="'ref'"></component>
      <br />
      子组件传来的值 : {{message}}
      <el-button @click="onclick">ref</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'test',
  data () {
    return {
      currentView: 'son-one',
      message: '',
      sendSon: 'component'
    }
  },
  components: {
    SonOne: () => import('./SonOne.vue')
  },
  created () {},
  mounted () {},
  methods: {
    onclick () {
      // 或者 let chil = this.$refs['ch']
      let chil = this.$refs.ch
      // 父组件可以通过$refs拿到子组件的对象
      // 然后直接调用子组件的 methods里的方法和data里的数据
      console.log(chil) // 子组件对象
      this.message = chil.message // 我是子组件的数据
      chil.sonMethod() // 我是子组件的方法
    },
    parentFn (payload) {
      this.message = payload
    }
  }
}
</script>

<style scoped="scoped">
</style>

子组件

<template>
<div>
    <el-input v-model="message" style="width: 15%;"/>
    <el-button @click="click" >Send</el-button>
</div>
</template>
<script>
export default {
  props: ['data'],
  data () {
    return {
      // 默认
      message: '我是来自子组件的消息'
    }
  },
  methods: {
    click () {
      if (this.data !== '') {
        this.message = JSON.parse(JSON.stringify(this.data))
      }
      this.$emit('childFn', this.message)
    },
    sonMethod () {
      this.$message('Son')
    }
  }
}
</script>

Vue风格指南实例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值