引言
vue3除了Composition API是一個亮點之外,尤大大又給我們帶來了一個全新的玩意 —— script setup,對於setup大家相信都不陌生,而對於script setup有些同學則表示難以理解,那么從現在開始,這一篇文章將讓你一看就懂。
ref與reactive
在setup中,我們擁有ref和reactive倆個api去創建一個響應式變量,這倆者存在的區別是ref是針對基本類型的響應,而reactive是針對引用類型的響應。
import { ref, reactive } from 'vue'
const data = ref('123')
const other = reactive({ is: '123' })
console.log(data.value)
console.log(other.is)
// 這里需要注意,reactive的對象可以直接訪問,修改內部的子數據,而data需要使用.value訪問修改,如下
data.value = '666' // ok
data = '666' // no
other.is = '666' // ok
other = '666' // no
導入自定義組件
在之前的optionApi中我們使用的是components: { ... } 的方式導入自定義組件,而在現在,我們只需要直接import組件即可使用
<template> <Button>OK!</Button> </template> <script setup> import Button from 'element-ui-plus' </script>
自定義方法
在之前的optionApi中我們使用的是在methods中寫自定義方法,而這里我們直接定義一個方法或者變量,在template中直接使用即可
<template>
<button @click="touchMe">OK!</button>
<button @click="touchIt">OK!</button>
</template>
<script setup>
import { ref, reactive } from 'vue'
const text = ref('123')
const touchMe = () => {
text.value = '666'
}
function touchIt() {
text.value = '666'
}
</script>
一般情況下筆者建議開發者都使用ref,因為ref適用范圍更廣。
全新的計算函數和watch
現在我們使用更為簡單的方式實現計算函數與watch,直接引入組合式api直接干就完了!
import { ref, computed, watch } from 'vue'
const data = ref('666')
const imComputed = computed(() => {
return data.value + 'some thing'
})
const unwatch = watch(data, () => {
console.log('data was be changed')
})
簡單直白的獲取到ref組件
之前我們采用this.$ref.refName的方式去獲取ref組件,在這里setup采用了更加簡單便捷的方式去獲取ref
<template>
<el-table ref="elTable"></el-table>
</template>
<script setup>
import { ref } from 'vue'
// refName = 變量名將自動捆綁進去
const elTable = ref(null)
console.log(elTable.value)
</script>
獲取props
之前的optionApi,我們需要先在props中定義props,然后再從this.xxx去獲取,這樣很容易出現重名覆蓋等情況,在這里vue3則采用了defineProps去定義props,直接返回了響應對象。
<script setup>
import { defineProps, toRefs, unref } from 'vue'
const props = defineProps({
a: {
default: 0
}
})
// 這里的a就等於從props中ref一個響應變量,需要.value操作符
const { a } = toRefs(props)
// 這里的a就等於從props中直接提取一個普通變量,隨意更改無響應,直接訪問無需.value
const { a } = unref(props)
</script>
至此,相信開發者看完大致就了解了script setup啦,在vue3時期快點擁抱組合式api,擁抱script setup,讓代碼看起來更簡潔點~
關於智密科技:專業開發各類Uniapp原生插件、目前交付給客戶的插件已經超過100個各類插件,正在陸續整理上架並分享一切關於Uni-app的教程、資訊。
插件使用交流QQ群:755910061
