vue3+Ts 之父子组件传值及部分函数基础使用·

vue3 基础

1. vue3,父组件向子组件传值(props)

父组件

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

显示
3s前
在这里插入图片描述
3s后
在这里插入图片描述

2. 创建响应式链接动态修改值(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. 跨层级组件间通信(provide,inject)

代码实现如下
传递参数的组件

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

显示效果
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值