天天看點

vue3 文法糖 defineProps defineEmits defineExpose

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怎麼擷取呢?setup script文法糖提供了新的API來供我們使用。

3.1 ​

​defineProps​

​​ 用來接收父元件傳來的 ​

​props​

​​。示例:

父元件

<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.2 ​

​defineEmits​

​​ 子元件向父元件事件傳遞。示例:

子元件

<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.3 ​

​defineExpose​

​​ 元件暴露出自己的屬性,在父元件中可以拿到。示例:

子元件

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

繼續閱讀