vue3语法糖script setup
在vue3种setup的写法,可以单独写setup()也可以写到script标签中,当然我们推荐后面这种
他的好处有很多,代码也简洁很多。
1、属性和方法无需return,可直接使用
/*原先*/ <script> import { defineComponent } from "vue" export default defineComponent({ name: 'app', setup() {
let a='bbb';
return{
a
} } }) </script> /*使用script-setup语法糖*/ <script name="app" setup>
let a='bbb';
</script>
2、import组件自动注册,无需写到components中
/*原先*/ <template> <about /> </template> <script> import about from './about.vue' import { defineComponent } from "vue" export default defineComponent({ name: 'home', components: { about } setup() { } }) </script> /*用script-setup语法糖后*/ <template> <about /> </template> <script> <script setup> import about from './about.vue' </script> //组件的引入使用已不再需要components注册才能使用了,直接引入就可以在tamplate使用了,这个更改让代码看起来更舒服简介了一些
3、组件使用的变化
props用法defineProps
//原来 props: { title: { type: String, default: '', required: true, }, }, //使用script-setup后
import {defineProps} from 'vue'
const props = defineProps({ title: { type: String, default: '', required: true, }, })
emit用法变化defineEmits
//原来 emit:['h-update','h-delete'] //使用script setup后 import { defineEmits } from 'vue' const emit = defineEmits(['h-update', 'h-delete'])
attrs和slot用法变化
//原来 setup(props,context){ const { attrs, slots, emit } = context // attrs 获取组件传递过来的属性值, // slots 组件内的插槽 } //使用script setup后 import { useContext } from 'vue' const { slots, attrs } = useContext()
组件对外暴露属性defineExpose
//子组件 <template> {{msg}} </template> <script setup> import { ref } from 'vue' let msg = ref("Child Components"); // defineExpose无需导入,直接使用 defineExpose({ msg }); </script> //父组件 <template> <Child ref="child" /> </template> <script setup> import { ref, onMounted } from 'vue' import Child from './components/Child.vue' let child = ref(null); onMounted(() => { console.log(child.value.msg); // Child Components }) </script>
4、使用自定义指令
全局注册的自定义指令将以符合预期的方式工作,且本地注册的指令可以直接在模板中使用,就像上文所提及的组件一样。
但这里有一个需要注意的限制:必须以 vNameOfDirective 的形式来命名本地自定义指令
,以使得它们可以直接在模板中使用
<script setup> const vMyDirective = { beforeMount: (el) => { // 在元素上做些操作 } } </script> <template> <h1 v-my-directive>This is a Heading</h1> </template> <script setup> // 导入的指令同样能够工作,并且能够通过重命名来使其符合命名规范 import { myDirective as vMyDirective } from './MyDirective.js' </script>
导入指令:
<script setup>
import { directive as clickOutside } from 'v-click-outside'
</script>
<template>
<div v-click-outside />
</template>