vue3
1.父组件传子组件
在父组件的子组件标签中定义一个属性,在子组件中用defineProps接收父组件传来的值
父组件
<template>
<div>
<sonOne msg="我是父组件的msg" @get-child-data="getChildData"></sonOne>
<!-- <p>{
{
num1}}</p>-->
</div>
</template>
<script setup lang="ts">
import {
ref,onMounted} from 'vue'
import sonOne from '@/components/sonOne.vue'
// var num1 =ref('')
// // 接收
// const getChildData = (data) => {
// console.log(data.value);
// num1.value = data.value
// }
</script>
<style scoped>
</style>
子组件
<template>
<div>
<p>我是父组件传过来的:{
{
msg}}</p>
<!-- <button @click="sendData">传递数据给父组件</button>-->
</div>
</template>
<script setup lang="ts">
import {
ref} from 'vue'
defineProps<{
msg
}>()
// const num = ref(123)
// const emits = defineEmits()
// emits('getChildData', num)
</script>
<style scoped>
</style>
1.子组件传父组件
在父组件的子组件标签中定义一个自定义事件,用自定义事件来接收子组件传来的参数,在子组件中用defineEmits向父组件传参
父组件
<template>
<div>
<sonOne msg="我是父组件的msg" @get-child-data="getChildData"></sonOne>
<p>{
{
num1}}</p>
</div>
</template>
<script setup lang="ts">
import {
ref,onMounted} from 'vue'
import sonOne from '@/components/sonOne.vue'
var num1 =ref('')
// 接收从子组件传来的参数
const getChildData = (data) => {
console.log(data.value);
num1.value = data.value
}
</script>
<style scoped>
</style>
子组件
<template>
<div>
<p>我是父组件传过来的:{
{
msg}}</p>
</div>
</template>
<script setup lang="ts">
import {
ref} from 'vue'
defineProps<{
msg
}>()
const num = ref(123)
// 子传父
const emits = defineEmits()
emits('getChildData', num)
</script>
<style scoped>
</style>
vue2
父组件传子组件
<div id='app'>
<!-- 父传子需要在父组件中的子组件中定义一个变量 -->
<son :type="father"></son>
</div>
<template id="son">
<div>
{
{
type}}
</div>
</template>
<script>
// 子组件
Vue.component('son',{
template:'#son',
// 在子组件中需要用props接收父组件的值
props:{
type:[String,Number]
},
})
// 父组件
const vm = new Vue({
el: '#app',
data: {
father:'父组件传给子组件的值'
},
methods: {
}
})
</script>
子组件传父组件
<div id='app'>
<!-- 子传父需要在父组件中的子组件中定义一个自定义事件 -->
<son @getson="getson"></son>
<h2>{
{
msg}}</h2>
</div>
<template id="son">
</template>
<script>
// 子组件
Vue.component('son',{
template:'#son',
data(){
return {
msg:'子传过来的值'
}
},
created(){
// 在子组件中用this.$emit传递参数 this.$emit(第一个参数 自定义事件的名字,第二个参数 传递的值)
this.$emit('getson',this.msg)
}
})
// 父组件
const vm = new Vue({
el: '#app',
data: {
msg:''
},
methods: {
// 自定义的事件名函数接收子传过来的值
getson(data){
this.msg = data
}
}
})
</script>
vue2和vue3父子组件传参的区别:
父传子:
vue2中父传子,父组件通过自定义属性发送,子组件通过
props
接收。
vue3中不同的是,父组件中引入子组件后,不需要注册可直接使用,子组件中通过defineProps
方法接收
子传父:
vue2中子传父,子组件通过
$emit
发送,父组件通过自定义事件接收。
vue3中不同的是,父组件中引入子组件后,不需要注册可直接使用,子组件中通过defineEmits
方法发送。