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>

感谢观看

vuejs
44 views
Comments
登录后评论
Sign In
·

组合式API用下来,感觉感觉就是全新的东西了。跟搞了新技术栈一样 这该死的新鲜感