一.父向子传递参数
1)父组件
<template>
<div>
<!-- info.msg 父组件向子组件传递的参数 -->
<son-component :msgTitme="info.msg"></son-component>
</div>
</template>
<script>
import SonComponent from "./SonComponent.vue"
import { reactive } from "vue";
export default {
components:{ SonComponent },
setup() {
const info = reactive({
msg:'hello world'
})
return {
info
}
}
}
</script>
2)子组件
<template> <div> 子组件 - {{ msgTitme }} </div> </template> <script> export default { props: { msgTitme:String } </script>
二. 子组件向父组件传值
1)父组件
<template>
<div>
<!-- clickParent 自定义方法(子组件向父组件传值需要的方法) -->
<son-component @clickParent="clickParent"></son-component>
<!-- info.options 父组件接收子组件的值 -->
<div>子向父传递的参数 - {{ info.options }} </div>
</div>
</template>
<script>
import SonComponent from "./SonComponent.vue"
import { reactive } from "vue";
export default {
components:{ SonComponent },
setup() {
const info = reactive({
msg:'hello world',
options:''
})
const clickParent = ( value )=>{
// value 子组件传过来的值
info.options = value
}
return {
info,
clickParent
}
}
}
</script>
2)子组件
<template>
<div>
<el-button @click="$emit('clickParent',info.msg)">直接调用</el-button>
<el-button @click="isClickParent">间接调用</el-button>
</div>
</template>
<script>
import { reactive } from "vue";
export default {
props: {
msgTitme:String
},
// emits:['clickParent'],
emits: {
clickParent: (value) => {
if (value) {
return true
} else {
return false
}
}
},
setup(props, { emit }) {
const info = reactive({ msg: 'hello 我是子传参数'})
const isClickParent = () =>{
emit('clickParent', info.msg )
}
return {
info,
isClickParent
}
},
}
</script>