018-父子组件传参和实践

程序员成长之旅 · 程序员成长之旅/Vue.js学习/Vue3/慕课网 - vue3.0实现todolist · 433 字

父子组件传参和实践


// @/compoment/Father.vue

<template>

<div>

Father.vue

<son :fatherMsg='fatherMsg' @sonSpk='sonSpeck'></son>

</div>

</template>

<script>

import { defineComponent, ref } from 'vue'

import Son from '@/compoment/son.vue'

export default defineComponent({

name: 'father',

conpoment: {

Son

},

setup(){

let fatherMsg = ref('Hi, I am father.')

let sonSpeck = (velue) => {

console.log('sonSpeck: ', value)

}

return{

fatherMsg

}

}

})

</script>

// @/compoment/Son.vue

<template>

<div>

Son.vue

<div>Father msg: {{fatherMsg}}</div>

<button @click='>子组件发送给父组件消息</button>

</div>

</template>

<script>

import { defineComponent, ref, onMonted } from 'vue'

export default defineComponent({

name: 'father',

//props: 接收父组件传递过来的参数

//props传递过来的数据可以直接在template中直接使用, 但是不能直接更改

props: {

fatherMsg: {

//type: 指定传入参数的类型, 会自动进行效验, 如果不符合会报错

type: String,

//required: 设置参数是否为必填

required: true,

//default: 设置默认值, 如果未传值, 则将调用默认值

default: '默认值'

}

}

//setup有两个参数 props, ctx

//props: 中可以接收父组件传递过来的值, 但是别忘了必须在上方声明

//ctx: 上下文, 可以用来调用父组件方法

setup(props, ctx){

//props.msg += ' Thank You!' x错误 不能直接props.msg修改

let fatherSpeak = ref(props.msg) //√正确 可以获取这个值给变量(修改不会更新到父组件)

fatherSpeak.value += ' Thank You!' //√正确 可以修改自己的变量, 并且在本组件内有动态更新

let sonMsg = ref('Hi! I am Son')

onMonted(() =>{

//使用ctx.emit可以调用父组件的方法并传递参数

//ctx.emit共有两个参数, 第一个参数是事件名称, 第二个参数是传递的参数

ctx.emit('sonSpk', sonMsg.value)

//ctx.emit的第二个参数还可以传递多个参数, 可以使用数组或者对象

ctx.emit('sonSpk', ['abc', sonMsg.value])

ctx.emit('sonSpk', {

msg: sonMsg.value,

letters: 'abc'

})

})

return{

fatherSpeak,

}

}

})

</script>