vue3 父子组件传参
父组件
<script setup lang="ts">
import HelloWorld from './components/HelloWorld.vue'
import { onMounted, ref } from 'vue'
// 传给子组件的值 在引用的组件里传递参数
const list:Array<number> = [1,2,3,4]
// 接收子组件的值 先用ref获取子组件
const HelloWorldRef = ref()
// 组件挂载时调用 onMounted
onMounted(()=>{
console.log(HelloWorldRef.value.toFather);
})
</script>
<template>
<div>
<HelloWorld :list="list" ref="HelloWorldRef" />
</div>
</template>
<style>
</style>
子组件
<script setup lang="ts">
import { ref } from "vue"
// 接收父組件的傳值 defineProps
// 第一種方法 默认值
const props = defineProps({
list:{
type: Array,
default:() => [4,5,6]
}
})
// 第二種方法 没有默认值
// 先定义接口 interface
interface Props {
list: Array<number>;
}
const props = defineProps<Props>()
// 父传子还有一种方法 可以参考上一篇vue2 vue3调用方法
// 传给子组件的值 先用defineExpose导出子组件的值
const toFather = ref('子组件的值')
defineExpose({toFather})
</script>
<template>
<div>
HelloWorld
</div>
</template>
<style scoped lang="scss">
</style>
vue2父子组件传参
父组件
<template>
<div class="home">
<!-- :list 向子组件传递参数 @fromSon是子组件自定义的方法-->
<HelloWorld :list="toSon" @fromSon="fromSon"/>
<button @click="changeToSon">改变传递的参数</button>
</div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'HomeView',
components: {
HelloWorld
},
data(){
return {
toSon: [1,2,3]
}
},
methods:{
// 改变传递的参数 触发子组件的监听事件watch
changeToSon(){
this.toSon = [4,5,6]
},
// 接收子组件的参数
fromSon(data){
console.log(data)
}
}
}
</script>
子组件
<template>
<div class="hello">
HelloWorld
<button @click="toFather">传参给父组件</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data(){
return {
msg: '子组件的值'
}
},
// 接收父组件传递的参数
props:{
list:{
type: [Array,String],
default(){
return [7,8,9]
}
}
},
// 监听事件 监听父组件传递参数改变
watch:{
list:{
handler(oldValue,newValue){
console.log(oldValue)
console.log(newValue)
},
deep: true
}
},
created() {
console.log(this.list)
},
methods:{
// 传递给子组件的方法
toFather(){
// 第一个参数自定义的方法,第二个参数为传递的参数
this.$emit('fromSon',this.msg)
}
}
}
</script>
<style scoped lang="less">
</style>