vue3中setup语法糖

1.setup语法糖,

最开始Vue3.0暴露变量的方法必须return出来,template中才能使用,现在只需在script标签中添加setup,组件只需引入,不用注册,属性方法也不用返回,也不用写setup函数,也不用写export default,甚至是自定义指令也可以在我们的template中自动获得.

<template>
  <my-component :num="num" @click="addNum" />
</template>

<script setup>
  import {
    
     ref } from 'vue';
  import MyComponent from './MyComponent .vue';

  // 像在平常的setup中一样的写,但是不需要返回任何变量
  const num= ref(0)       //在此处定义的 num 可以直接使用
  const addNum= () => {
    
       //函数也可以直接引用,不用在return中返回
    num.value++
  }
</script>

2.使用 setup组件自动注册:

在script setup中,引入的组件可以直接使用,无需再通过components进行注册,并且无法指定当前组件的名字,它会自动以文件名字为主,也就是不用在写name属性了.

实例:

<template>
    <zi-hello></zi-hello>
</template>

<script setup>
  import ziHello from './ziHello'
</script>

3.使用setup后新增API:

因为没有setup函数,那么props,emit怎么获取呢? script setup语法糖提供了新的API来供我们使用

3.1、defineProps用来接收父组件创来的peops 实例:
  • 父组件
<template>
  <div class="die">
    <h3>我是父组件</h3>
    <zi-hello :name="name"></zi-hello>
  </div>
</template>

<script setup>
  import ziHello from './ziHello'
  import {
      
      ref} from 'vue'
  let name = ref('我是父组件')
</script>
  • 子组件
<template>
  <div>
    我是子组件{
    
    {
    
    name}}
  </div>
</template>

<script setup>
  import {
    
    defineProps} from 'vue'
  defineProps({
    
    
   name:{
    
    
     type:String,
     default:'我是默认值'
   }
 })
</script>
3.2defineEmits子组件向父组件事件传递. 实例:
  • 子组件
<template>
  <div>
    我是子组件{
   
   {name}}
    <button @click="ziupdata">按钮</button>
  </div>
</template>

<script setup>
  import {
      
      defineEmits} from 'vue'

  //自定义函数,父组件可以触发
  const em=defineEmits(['updata'])
  const ziupdata=()=>{
      
      
    em("updata",'我是子组件的值')
  }

</script>
  • 父组件
<template>
  <div class="die">
    <h3>我是父组件</h3>
    <zi-hello @updata="updata"></zi-hello>
  </div>
</template>

<script setup>
  import ziHello from './ziHello'
  const updata = (data) => {
      
      
    console.log(data); //我是子组件的值
  }
</script>
3.3defineExpose组件暴露出自己的属性,在父组件中可以拿到。示例:
  • 子组件
<template>
  <div>
    我是子组件
  </div>
</template>

<script setup>
  import {
      
      defineExpose,reactive,ref} from 'vue'
  let ziage=ref(18)
  let ziname=reactive({
      
      
    name:'xxxx'
  })
  //暴露出去的变量
  defineExpose({
      
      
    ziage,
    ziname
  })
</script>
  • 父组件
<template>
  <div class="die">
    <h3 @click="isclick">我是父组件</h3>
    <zi-hello ref="zihello"></zi-hello>
  </div>
</template>

<script setup>
  import ziHello from './ziHello'
  import {
      
      ref} from 'vue'
  const zihello = ref()
  const isclick = () => {
      
      
    console.log('接收ref暴漏出来的值',zihello.value.ziage)
    console.log('接收reactive暴漏出来的值',zihello.value.ziname.name)
  }
</script>

注意:用setup语法糖时,getCurrentinstance线上可能会失效

猜你喜欢

转载自blog.csdn.net/weixin_53156345/article/details/130622887