vue3 实验属性 script setup <script setup>

公司一直使用的都是vue2.x,在vue conf 中看尤大演示 script setup 让我眼前一亮,这种简便语法太吸引了。

示例

在不使用script setup,我们代码是:

<template>
	<h1 v-text="count"></h1>
	<p v-text="double"></p>
  <button @click="add">count++</button>
</template>

<script>
import { ref, unref, computed } from 'vue'
export default {
  setup() {
    const count = ref(1)
    const double = computed(() => unref(count) * 2)
    function add() {
      count.value++
    }
    return {
      count,
      double,
      add
    }
  }
}
</script>

使用了 script setup 之后,实现一样的功能,代码如下:

<template>
	<h1 v-text="count"></h1>
	<p v-text="double"></p>
  <button @click="add">count++</button>
</template>

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

const count = ref(1)
const double = computed(() => unref(count) * 2)
function add() {
  count.value++
}
</script>

组件使用

在 script setup 中 所以组件导入即自动注册:

<template>
  <Test :msg="msg"/>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import Test from './components/test.vue'
const msg = ref('msg')
</script>

省去了组件的注册步骤,也没有显式的导出变量的动作。

使用props & emit & useContext

<template>
  <button @click="emit('setData', Number.parseInt(Math.random() * 10))">添加数据</button>
</template>

<script setup>
import { defineEmit, defineProps } from 'vue'
// defineProps(['list'])
const props = defineProps({
  list: {
    type: Array,
    default: () => []
  }
})
const emit = defineEmit(['deleteData', 'setData'])
const { slots , attrs } = useContext()
</script>

1.props 需要使用到 defineProps 来定义,用法跟之前的props写法类似
2.emit 使用 defineEmit 定义组件可以发出的事件
3.useContext 访问组件的槽和属性
4.defineProps/defineEmit 会根据传递的值做简单的类型推断

指令

指令跟组件是一样导入就自动注册。

<template>
  <div v-click-outside />
</template>

<script setup>
  import { directive as clickOutside } from 'v-click-outside'
</script>

inheritAttrs

<template inherit-attrs="false"></template>

默认值true,在这种情况下父作用域的不被认作 props 的特性绑定 (attribute bindings) 将会“回退”且作为普通的 HTML 特性应用在子组件的根元素上

await

如果使用了 await 那么 需要 与 Suspense 异步组件 搭配使用

/* 父组件 */
<Suspense>
   <template #default>
     <AwaitComponent />
   </template>
   <template #fallback>
       loading....
   </template>
</Suspense>
<template>
  <h1>{{ result }}</h1>
</template>

<script lang="ts">
import { ref } from "vue";
const result = ref("")
function promiseFun () {
	return new Promise((resolve, reject) => {
		setTimeout(() => resolve('22322323'), 3000)
	})
}
result.value = await promiseFun()
</script>

感谢观看

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值