2022-04-17
阅读:55
props
<!--父组件 -->
<template>
<Children name="123"></Children>
</template>
<!-- 子组件Children -->
<template>
<div>
{{name}}
</div>
</template>
<script>
export default {
props:{//父组件传递过来的参数
name:{
type:string,
default:''
}
}
}
</script>
$emit
<!--父组件-->
<template>
<Children @change="handleChange"></Children>
</template>
<script>
export default {
methods:{
handleChange(data){//自定义事件接收子组件传递的参数
console.log(data)
}
}
}
</script>
<!--子组件-->
<template>
<button @click="subChange">发送数据给父组件</button>
</template>
<script>
export default {
methods:{
subChange(){
this.$emit('change','张三')
}
}
}
</script>
provide/inject
这对选项需要一起使用,以允许一个祖先组件向其所有子孙后代注入一个依赖,不论组件层次有多深,并在其上下游关系成立的时间里始终生效。如果你熟悉 React,这与 React 的上下文特性很相似。
简单来说,可以实现祖先组件向其后代所有子孙组件传参
例如:
<!-- 祖先组件 -->
<template>
<div>
<Children>
<Sun></Sun>
</Children>
</div>
</template>
<script>
export default{
provide:{//祖组件中定义provide
name:'张三'
}
}
</script>
provide
选项应该是一个对象或返回一个对象的函数。该对象包含可注入其子孙的 property。在该对象中你可以使用 ES2015 Symbols 作为 key,但是只在原生支持Symbol
和Reflect.ownKeys
的环境下可工作。
<!-- 子孙组件 -->
<template>
<div>
{{name}}
</div>
</template>
<script>
export default{
inject:['name'],//使用祖组件中注入的name
}
</script>