关于uni-app:拥抱简洁代码vue3中的script-setup最强解析

13次阅读

共计 1865 个字符,预计需要花费 5 分钟才能阅读完成。

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,让代码看起来更简洁点~

正文完
 0