【父子组件传值】Vue子父组件传值的三种方法

父组件向子组件传值: props-父组件给子组件传输数据和验证

1.父组件的代码示例

<template>
<div>父组件</div>
// 引用子组件
<Dialog :fatherData="fatherData"></Dialog>
</template>

<script>
// 导入子组件
import Dialog from '@/components/Dialog.vue'

export default {
    
    
  name: 'HomeView',
  components: {
    
     Dialog },
  data () {
    
    
    return {
    
    
      fatherData: '父组件的值',
    }
  }
}
</script>

2.子组件的代码示例

<template>
  <div>
    <div>子组件</div>
    <div>
    //展示父组件数据
      {
    
    {
    
    fatherData}}
    </div>
  </div>
</template>
<script>
export default {
    
    
  data () {
    
    
    return {
    
    
      childrenData: '子组件自己的数据'
    }
  },
  //props的基本用法是父组件给子组件传输数据和验证
  props: {
    
    
  //父组件数据
    fatherData: {
    
    
      type: String
    }
  }
}
</script>

子组件向父组件传值:this.$emit()-子组件可以使用 $emit,让父组件监听到自定义事件

1.父组件的代码示例

<template>
<div>父组件</div>
// 引用子组件
<Dialog  @tranferData="tranferData"></Dialog>
//展示子组件的值
<div>{
    
    {
    
     receiveData }}</div>
</template>

<script>
// 导入子组件
import Dialog from '@/components/Dialog.vue'

export default {
    
    
  name: 'HomeView',
  components: {
    
     Dialog },
  data () {
    
    
    return {
    
    
      fatherData: '父组件的值',
      receiveData:''
    }
  },
  methods: {
    
    
  //接收子组件传过来的数据
  tranferData(val){
    
    
  	console.log('子组件向父组件传过来的值:',val)
  	this.receiveData = val
  }
  }
}
</script>

2.子组件的代码示例

<template>
  <div>
    <div>子组件</div>
    <el-button @click="tranfer">子向父传值</el-button>
  </div>
</template>
<script>
export default {
    
    
  data () {
    
    
    return {
    
    
      childrenData: '子组件的值'
    }
  }
  },
  methods:{
    
    
  	tranfer(){
    
    
  	this.$emit('tranferData',this.childrenData)
  	}
  }
}
</script>

通过 r e f s 调用子组件的值 − 用 t h i s . refs调用子组件的值-用this. refs调用子组件的值this.refs 获取到的是组件实例,可以使用组件的所有方法

1.父组件的代码示例

<template>
<div>父组件</div>
// 引用子组件
<Dialog ref='dialogData'></Dialog>
<div>通过refs拿到子组件的值</div>
<el-button @click="toGet">refs拿到子组件的值</el-button>
</template>

<script>
// 导入子组件
import Dialog from '@/components/Dialog.vue'

export default {
    
    
  name: 'HomeView',
  components: {
    
     Dialog },
  data () {
    
    
    return {
    
    
      fatherData: '父组件的值',
    }
  },
  methods:{
    
    
  toGet(){
    
    
  	 // 通过refs调用子组件的值(childrenData)
    	const data = this.$refs.dialogData.childrenData
     	alert(data)
     //  通过refs调用子组件的值(childrenWay())
     	const way = this.$refs.dialogData.childrenWay()
     	alert(way)
  }
  }
}
</script>

2.子组件的代码示例

<template>
  <div>
    <div>子组件</div>
  </div>
</template>
<script>
export default {
    
    
  data () {
    
    
    return {
    
    
      childrenData: '子组件自己的数据'
    }
  },
  methods:{
    
    
  childrenWay(){
    
    
  	alert('父组件调用子组件的方法')
  }
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/YYYi_z/article/details/129288996