父组件
<template>
<h1>
父传子
h1>
//应用组件
<ChildComp
name="父组件传递的值"
msg="父组件信息---》我传过来了"
/>
template>
<script lang="ts">
import {defineComponent} from 'vue'
//1.导入组件
import ChildComp from "./Child.vue";
export default defineComponent({
//2.使用组件
components: {ChildComp},
setup(props) {
return {}
}
})
script>
子组件
<template>
<span>参数传递 父----》子span>
<h1>{{name}}h1>
<h1>{{msg}}h1>
template>
<script lang="ts">
import {defineComponent,ref} from 'vue'
const name:any=ref("子组件name");
const msg:any=ref("子组件msg");
export default defineComponent({
//1.给子组件命名
name:"ChildComp",
//2.父组件传入值
props: {
name: String,
msg: {type: String, required: true}
},
setup(props,context){
//3.拿到值 或者 不写但是return不写
setTimeout(function () {
name.value=props.name;
msg.value=props.msg;
},3000)
return{
name,
msg,
}
}
})
script>
<template>
<h1>
创建连接
h1>
{{data}}
{{foo}}
<button @click="change">
按钮
button>
template>
<script lang="ts">
import {defineComponent,reactive,toRef} from 'vue'
import ChildComp from "./Child.vue";
const data = reactive({
name:"xiaoli",
sex:"男"
});
const foo = toRef(data,'sex');
export default defineComponent({
components: {ChildComp},
setup(props) {
function change(){
//data.sex.value="女--->";//错误
foo.value="女";
console.log(foo);
}
return {
data,
foo,
change,
}
}
})
script>
代码实现如下
传递参数的组件
<template>
<h1>
跨层级组件通信
h1>
//接收参数的组件
<Comp/>
template>
<script setup>
import { ref,provide } from 'vue'
import Comp from './Comp.vue'
const color = ref('red');
provide("color",color)
script>
接收参数的组件
<template>
<h1>
父组件传值来了{{color}}
h1>
template>
<script setup>
import { ref,inject } from 'vue'
const color = inject("color");
script>