Vue3 script setup 的使用
注意:需要
Vue 3.2
版本以上
- Vue3 引入了 composition API
- composition API 最重要的是 setup 函数
<script>
只有一个 setup 函数太“孤单”,如何简化一下?
基本使用
- 顶级变量、自定义组件,可以直接用于模板
- 可以正常使用 ref reactive computed 等能力
- 和其他
<script>
同时使用
例子,定义一个 Child.vue
html
<template>
<p>child</p>
</template>
<script>
export default {
name: 'Child',
};
</script>
然后在 Index.vue
中使用
html
<script>
function add(a, b) {
return a + b;
}
</script>
<script setup>
import { reactive, ref, toRefs } from 'vue';
import Child from './Child';
const countRef = ref(100);
// 直接使用,不需要 return
function addCount() {
countRef.value++;
}
const state = reactive({
name: 'lzw.',
});
// 直接使用,不需要 return
const { name } = toRefs(state);
// 直接使用其他 script 函数
const addVal = add(1, 2);
</script>
<template>
<p @click="addCount">
vue3.2+ script setup {{ countRef }} {{ name }} {{ addVal }}
</p>
<!-- 直接引入使用,不需要注册了-->
<Child></Child>
</template>
属性和事件
- defineProps
- defineEmits
还是定义一个子组件 Child.vue
html
<script setup>
import { defineProps, defineEmits } from 'vue';
// 定义属性
const props = defineProps({
name: String,
age: Number,
});
// 定义事件
const emits = defineEmits(['change', 'delete']);
function deleteHandler() {
emits('delete', '删除');
}
</script>
<template>
<p>child - {{ props.name }} {{ props.age }}</p>
<button @click="$emit('change','修改')">change</button>
<button @click="deleteHandler">delete</button>
</template>
然后在 Index.vue
中使用
html
<script setup>
import Child from './Child';
function onChange(info) {
console.log('on change', info);
}
function onDelete(info) {
console.log('on delete', info);
}
</script>
<template>
<!-- 直接引入使用,不需要注册了-->
<Child name="name" age="20" @change="onChange" @delete="onDelete"></Child>
</template>
暴露组件信息 defineExpose
还是定义一个子组件 Child.vue
html
<script setup>
import { ref, defineExpose } from 'vue';
const a = ref(100);
const b = 200;
defineExpose({
a,
b,
});
</script>
然后在 Index.vue
中使用
html
<script setup>
import { onMounted } from 'vue';
import Child from './Child';
const childRef = ref(null);
onMounted(() => {
// 拿到 child 组件的一些数据
console.log(childRef.value.a);
console.log(childRef.value.b);
});
</script>
<template>
<!-- 直接引入使用,不需要注册了-->
<Child ref="childRef"></Child>
</template>