vue3 父组件
在父组件中的子标签中定义一个 属性名:属性值,在子组件中用defineProps接收
<template>
<div>
<TheWelcome msg="给子组件传的值" @zidingyi="receive"></TheWelcome>
<div> 子组件给父组件传的参数----{{jiehsou}}</div>
</div>
</template>
<script setup lang="ts">
import TheWelcome from '../components/TheWelcome.vue'
import {ref} from 'vue'
let jiehsou = ref('')
const receive = (data:String) =>{
jiehsou.value = data
console.log(data)
}
</script>
vue3 子组件
在父组件的子标签中写自定义事件,在子组件中写一个点击事件,再定义emit,emit的第一个参数是父组件的方法,第二参数就是需要传递的值
<template>
<div class="greetings">
接收父组件传的参----{{msg}}
<button @click="btn">给父组件传参</button>
</div>
</template>
<script setup lang="ts">
import {defineEmits} from 'vue'
defineProps({
msg:String,
})
const emits = defineEmits(["zidingyi"])
const btn = () => {
emits('zidingyi',"子组件给父组件传的参数")
};
</script>
<style scoped>
</style>
vue2 的父组件
props:在父组件中,给子组件绑定一个自定义属性,在子组件中,通过props进行接收
<template>
<div class="home">
<HelloWorld msg="父传子" @zidinbyi="zidinbyi"/>
接收子组件传来的值---------{{shuju}}
</div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'HomeView',
components: {
HelloWorld
},
data(){
return{
shuju:''
}
},
methods:{
zidinbyi(data){
this.shuju = data
}
}
}
</script>
vue2子组件
自定义事件:在父组件中,给子组件绑定一个自定义事件,绑定事件的值为接收参数的函数,在子组件中,通过$emit发送数据
<template>
<div class="hello">
接收父组件传值---------{{msg}}
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
msg: String
},
created() {
this.$emit('zidinbyi','子组件给父组件传的值')
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
</style>