Vue3+Ts parent-child component value transfer and basic use of some functions

vue3 basics

1. Vue3, the parent component passes the value (props) to the child component

parent component

<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>

Subassembly

<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>

Display
3s before
insert image description here
3s after
insert image description here

2. Create a responsive link to dynamically modify the value (toRef)

<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>

3. Communication between cross-level components (provide, inject)

The code implementation is as follows
Components that pass parameters

<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>

Components that receive parameters

<template>
  <h1>
    父组件传值来了{
   
   {color}}
  </h1>
</template>

<script setup>
import {
      
       ref,inject } from 'vue'
const color = inject("color");

</script>

display effect
insert image description here

Guess you like

Origin blog.csdn.net/qq_44774287/article/details/126479187