vue3.0的父子组件之前的传值
父传子
props
父组件:
<template>
<Child :title='state'/>
</template>
<script setup>
import { reactive } from 'vue'
import Child from '../components/HelloWorld.vue'
const state=reactive({
title:'你好'
})
</script>
子组件:
<template>
我是子组件{{title}}
</template>
<script >
import { defineComponent } from 'vue'
export default defineComponent({
//或者props:['title'],
props:{
title:{
type:String,
default:''
}
},
setup() {
},
})
</script>
- 使用
setup
语法糖<script setup>
中必须使用defineProps
和defineEmits
API 来声明props
和emits
<template>
我是子组件{{title}}
</template>
<script setup>
//或者 defineProps(['title'])
defineProps({
title:{
type:String,
default:''
}
})
- 使用
provide
和inject
支持多层父子级嵌套,深层套娃使用子组件的时候更佳
父组件
<template>
<Child />
</template>
<script setup>
import Child from '../components/HelloWorld.vue'
import { reactive,provide } from 'vue'
const state=reactive({
title:'你好'
})
//声名provide
provide('provideToChild', {
state,
changeTitle: (FromChildParams) => {
state.title=FromChildParams
}
})
// provide('provideToChild',state )
</script>
子组件
<template>
我是子组件{{injectFromParent}}
</template>
<script>
import { defineComponent,inject } from 'vue'
export default defineComponent({
setup() {
const injectFromParent= inject('provideToChild');
//子组件调用父组件传递过来的函数同时携带参数给父组件
injectFromParent.changeTitle('MontherFucker');
return {
injectFromParent
}
},
})
</script>
//或者------------------
<template>
我是子组件{{injectFromParent}}
</template>
<script setup>
import {inject} from 'vue'
//注入
const injectFromParent= inject('provideToChild');
injectFromParent.changeTitle('MontherFucker');
</script>
子传父
- 上面已经讲述了,inject方式向父级传参
setup
语法糖中的defineEmits
,2.0中的传值方式不再赘述
父组件
<template>
<Child @toSonEvent='changeTitle'/>
<div>{{state}}</div>
</template>
<script setup>
import Child from '../components/HelloWorld.vue'
import { reactive,provide } from 'vue'
const state=reactive({
title:'你好'
})
const changeTitle=(fromSonParams)=>{
//接收子组件传递过来的参数
state.title=fromSonParams
}
</script>
<template>
我是子组件
<button @click='changeFatherTitle'>触发子组件传递过来的数据并且向他传值</button>
</template>
<script setup>
const fromFather = defineEmits(['toSonEvent'])
const changeFatherTitle=()=>{
//向父组件传递参数
fromFather('toSonEvent','montherFucker')
}
</script>
3.
v-model
传值
父组件
<template>
<Child v-model:title="state.title" v-model:name="state.name"/>
<div>{{state.title}}</div>
<div>{{state.name}}</div>
</template>
<script setup>
import Child from '../components/HelloWorld.vue'
import { reactive } from 'vue'
const state=reactive({
title:'你好',
name:'尼古拉斯.jack'
})
</script>
<template>
我是子组件
<button @click='changeInfo'>触发子组件传递过来的数据并且向他传值</button>
</template>
<script setup>
defineProps(['title','name']);
const $emit = defineEmits(['update:title','update:name'])
const changeInfo=()=>{
$emit('update:title','montherFucker')
$emit('update:name','赵四')
}
</script>