setup语法糖

在vue3.0中,setup函数中的变量必须return出来才能给template使用,3.2中使用setup语法糖无需return变量就可以在template中使用了,而且引入的组件可以直接使用,无需再通过components进行注册。setup 语法糖中可直接使用 await,不需要写 async , setup 会自动变成 async setup

父子组件传值props,子组件给父组件传值emit

父组件

<script setup>
  import HelloWorld from "./components/HelloWorld.vue"
  import {ref} from "vue"
  const msg=ref("父组件传值")
  let message=ref("")
  const go=(val)=>{
    message.value=val
  }
</script>

<template>
 <HelloWorld :msg="msg" @event="go"></HelloWorld>
  {{message}}

</template>

子组件

<script setup>
    import {ref} from "vue"
    const msg=ref("父组件传值")
    const emit=defineEmits(["event"])
    const btn=()=>{
        emit("event","子组件的值")
    }
</script>

<template>
    <h>{{msg}}</h><br>
    <h>我是子组件</h><br>
    <button @click="btn">子组件传值</button>
</template>

provide 和 inject 祖孙传值

父组件

<script setup>
  import HelloWorld from "./components/HelloWorld.vue"
  import {ref} from "vue"
  import {provide} from "vue"
  const name=ref("张飞")
  provide("provideData",{
    name
  })
</script>

<template>
 <HelloWorld ></HelloWorld>
</template>

子组件

<script setup>
    import {inject} from "vue"
  const provideData=inject("provideData")

</script>

<template>
    <h>{{provideData.name}}</h><br>
</template>

toRefs的使用

只能搭配Reactive,不能搭配Ref

<script setup>
  import HelloWorld from "./components/HelloWorld.vue"
  import {ref,reactive,toRefs} from "vue"
  const state=reactive({
    username:"root"
  })
  const {username}=toRefs(state)
  const change=()=>{
   username.value=""
  }
</script>

<template>
 {{username}}<br>
  <button @click="change">改变</button>
</template>

Watch函数(这个函数代码为了省事引用某博文)

  watch(
            ()=>message.value,
            (val,preVal)=>{
                //val为修改后的值,preVal为修改前的值
                console.log("message",val,preVal)
            },
            {
                //如果加了这个参数,值为true的话,就消除了惰性,watch会在创建后立即执行一次
                //那么首次执行,val为默认值,preVal为undefined
                immediate:true,
                //这个参数代表监听对象时,可以监听深度嵌套的对象属性
                //比如message是一个对象的话,可以监听到message.a.b.c,也就是message下的所有属性
                deep:true,
            }
        )
   watch(
            ()=>[message.value,count.value],
            ([messageVal,messagePreVal],[countVal,countPreVal])=>{
                //监听多个源用数组传入
                console.log("messageVal,messagePreVal",messageVal,messagePreVal)
                console.log("countVal,countPreVal",countVal,countPreVal)
            },
        )
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山河亦问安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值