Vue3.2 setup語法糖總結

Vue3.2 setup語法糖總結

在 Vue3.2 中只需要在 script 標籤上加上 setup 屬性,無需 return,template 便可直接使用,非常的香啊!

最後更新 2022/5/19 上午6:47
玲小叮当
預計閱讀 6 分鐘
分類
前端
標籤
Vue

前言

提示:Vue3.2 版本開始才能使用語法糖!

Vue3.0 中變數必須 return 出來,template 中才能使用;而在 Vue3.2 中只需要在 script 標籤上加上 setup 屬性,無需 returntemplate 便可直接使用,非常的香啊!

提示:以下是本篇文章正文內容,下面案例可供參考

一、如何使用 setup 語法糖

只需在 script 標籤上寫上 setup

代碼如下(範例):

<template>
</template>
<script setup>
</script>
<style scoped lang="less">
</style>

二、data 資料的使用

由於 setup 不需寫 return,所以直接聲明資料即可

代碼如下(範例):

<script setup>
    import {
      ref,
      reactive,
      toRefs,
    } from 'vue'

    const data = reactive({
      patternVisible: false,
      debugVisible: false,
      aboutExeVisible: false,
    })

    const content = ref('content')
    //使用 toRefs 解構
    const { patternVisible, debugVisible, aboutExeVisible } = toRefs(data)
</script>

三、method 方法的使用

代碼如下(範例):

<template >
    <button @click="onClickHelp">系統幫助</button>
</template>
<script setup>
import {reactive} from 'vue'

const data = reactive({
      aboutExeVisible: false,
})
// 點擊幫助
const onClickHelp = () => {
    console.log(`系統幫助`)
    data.aboutExeVisible = true
}
</script>

四、watchEffect 的使用

代碼如下(範例):

<script setup>
import {
  ref,
  watchEffect,
} from 'vue'

let sum = ref(0)

watchEffect(()=>{
  const x1 = sum.value
  console.log('watchEffect 所指定的回調執行了')
})
</script>

五、watch 的使用

代碼如下(範例):

<script setup>
    import {
      reactive,
      watch,
    } from 'vue'
     //資料
     let sum = ref(0)
     let msg = ref('你好啊')
     let person = reactive({
                    name:'張三',
                    age:18,
                    job:{
                      j1:{
                        salary:20
                      }
                    }
                  })
    // 兩種監聽格式
    watch([sum,msg],(newValue,oldValue)=>{
            console.log('sum 或 msg 變了',newValue,oldValue)
          },{immediate:true})

     watch(()=>person.job,(newValue,oldValue)=>{
        console.log('person 的 job 變化了',newValue,oldValue)
     },{deep:true})

</script>

六、computed 計算屬性的使用

computed 計算屬性有兩種寫法(簡寫和考慮讀寫的完整寫法)

代碼如下(範例):

<script setup>
    import {
      reactive,
      computed,
    } from 'vue'

    //資料
    let person = reactive({
       firstName:'小',
       lastName:'叮噹'
     })
    // 計算屬性簡寫
    person.fullName = computed(()=>{
        return person.firstName + '-' + person.lastName
      })
    // 完整寫法
    person.fullName = computed({
      get(){
        return person.firstName + '-' + person.lastName
      },
      set(value){
        const nameArr = value.split('-')
        person.firstName = nameArr[0]
        person.lastName = nameArr[1]
      }
    })
</script>

七、props 父子傳值的使用

子組件代碼如下(範例):

<template>
  <span>{{props.name}}</span>
</template>

<script setup>
  import { defineProps } from 'vue'
  // 聲明 props
  const props = defineProps({
    name: {
      type: String,
      default: '11'
    }
  })
  // 或者
  //const props = defineProps(['name'])
</script>

父組件代碼如下(範例):

<template>
  <child :name='name'/>
</template>

<script setup>
    import {ref} from 'vue'
    // 引入子組件
    import child from './child.vue'
    let name= ref('小叮噹')
</script>

八、emit 子父傳值的使用

子組件代碼如下(範例):

<template>
   <a-button @click="isOk">
     確定
   </a-button>
</template>
<script setup>
import { defineEmits } from 'vue';

// emit
const emit = defineEmits(['aboutExeVisible'])
/**
 * 方法
 */
// 點擊確定按鈕
const isOk = () => {
  emit('aboutExeVisible');
}
</script>

父組件代碼如下(範例):

<template>
  <AdoutExe @aboutExeVisible="aboutExeHandleCancel" />
</template>
<script setup>
import {reactive} from 'vue'
// 導入子組件
import AdoutExe from '../components/AdoutExeCom'

const data = reactive({
  aboutExeVisible: false,
})
// content 組件 ref


// 關於系統隱藏
const aboutExeHandleCancel = () => {
  data.aboutExeVisible = false
}

</script>

九、獲取子組件 ref 變數和 defineExpose 暴露

即 vue2 中的獲取子組件的 ref,直接在父組件中控制子組件方法和變數的方法

子組件代碼如下(範例):

<template>
    <p>{{data }}</p>
</template>

<script setup>
import {
  reactive,
  toRefs
} from 'vue'

/**
 * 資料部分
 * */
const data = reactive({
  modelVisible: false,
  historyVisible: false,
  reportVisible: false,
})
defineExpose({
  ...toRefs(data),
})
</script>

父組件代碼如下(範例):

<template>
    <button @click="onClickSetUp">點擊</button>
    <Content ref="content" />
</template>

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

// content 組件 ref
const content = ref('content')
// 點擊設置
const onClickSetUp = ({ key }) => {
   content.value.modelVisible = true
}

</script>
<style scoped lang="less">
</style>

十、路由 useRoute 和 useRouter 的使用

代碼如下(範例):

<script setup>
  import { useRoute, useRouter } from 'vue-router'

  // 聲明
  const route = useRoute()
  const router = useRouter()

  // 取得 query
  console.log(route.query)
  // 取得 params
  console.log(route.params)

  // 路由跳轉
  router.push({
      path: `/index`
  })
</script>

十一、store 倉庫的使用

代碼如下(範例):

<script setup>
  import {useStore} from 'vuex' import {num} from '../store/index' const store =
  useStore(num) // 取得 Vuex 的 state console.log(store.state.number) //
  取得 Vuex 的 getters console.log(store.state.getNumber) // 提交 mutations
  store.commit('fnName') // 分發 actions 的方法 store.dispatch('fnName')
</script>

十二、await 的支援

setup 語法糖中可直接使用 await,不需要寫 async , setup 會自動變成 async setup

代碼如下(範例):

<script setup>
  import Api from '../api/Api' const data = await Api.getData()
  console.log(data)
</script>

十三、provide 和 inject 祖孫傳值

父組件代碼如下(範例):

<template>
  <AdoutExe />
</template>

<script setup>
  import { ref,provide } from 'vue'
  import AdoutExe from '@/components/AdoutExeCom'

  let name = ref('Jerry')
  // 使用 provide
  provide('provideState', {
    name,
    changeName: () => {
      name.value = '小叮噹'
    }
  })
</script>

子組件代碼如下(範例):

<script setup>
  import {inject} from 'vue' const provideState = inject('provideState')
  provideState.changeName()
</script>

總結

提示:這裡對文章進行總結:

例如:以上就是我自己找部落格什麼的學習 setup 語法糖進行的總結,在專案中都進行了使用是可以實現的,如果哪裡我寫錯了或者我的方法使用不對大家告訴我,我會馬上改噠!如果大家覺得我寫的文章還可以用很實用,歡迎大家點讚收藏關注呀關注博主不迷路哦!工作不忙的話會持續更新噠!歡迎大家看看小叮噹的其他文章~

繼續探索

延伸閱讀

更多文章
同分類 / 同標籤 2023/10/16

.NET工具箱:開源、免費的純前端工具網站,帶你探索10大工具分類和73個實時在線小工具

Dotnet工具箱是一個純前端的、開源和免費的工具網站,週末我參考了開源專案it-tools,對網站界面文字進行了中文化,並重新部署了網站。該網站共有10大工具分類,提供了73個實時在線小工具。使用Vue3開發的Dotnet工具箱具有獨特的特色,本文詳細介紹了其中一些特色工具,並簡單分享了如何部署自己的工具網站。如果你對工具網站感興趣,不妨來了解一下Dotnet工具箱吧!

繼續閱讀