Vue3的script setup语法糖这么好用的吗????
最近发现这个vue3居然还可以这样写
- 原始写法
<template>
<h1>Tangdoudou</h1>
<h1>{{ num }}</h1>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'App',
setup() {
const num = 123;
return { num };
},
});
</script>
- 等同于 (注意观察我注释掉的东西)
<template>
<h1>Tangdoudou</h1>
<h1>{{ num }}</h1>
</template>
<script setup>
// import { defineComponent } from 'vue';
// export default defineComponent({
// name: 'App',
// setup() {
const num = 123;
// return { num };
// },
// });
</script>
- 我直接把lang=ts去了,但是我们可以选择其他方式:
- 在script setup 中使用defineProps,defineEmits会报未定义,需要配置eslint
- 根据官网配置
- 链接:https://eslint.vuejs.org/user-guide/#faq
- 代码
'vue/setup-compiler-macros': true
响应式数据
<template>
<h3>响应式数据</h3>
<h3>{{ str }}</h3>
</template>
<script setup>
import { ref } from 'vue';
var str = ref('11122334');
</script>
点击改变数据
<template>
<h3>响应式数据</h3>
<h3>{{ str }}</h3>
<button @click="str += '数据变啦~'">点击改变str</button>
</template>
<script setup>
import { ref } from 'vue';
var str = ref('11122334');
</script>
父子组件传值
- 子组件
<template>
<div style="background-color: pink">
<h4>这个是子组件的内容</h4>
<button @click="onMyClick">点击后传输信息给父组件</button>
<h4>这是父组件传入的信息:{{ msg }}</h4>
</div>
</template>
<script >
// 声明一些额外的配置选项
export default {
name: 'ChildPage',
};
</script>
<script setup>
const props = defineProps({
msg: String,
});
// 定义emit事件
const emit = defineEmits({
childFun: null,
});
function onMyClick() {
emit('childFun', { val: '我是子组件的值~啦啦啦~~' });
}
</script>
- 父组件
<template>
<h3>响应式数据</h3>
<h3>{{ str }}</h3>
<button @click="str += '数据变啦~'">点击改变str</button>
<ChildPage msg="1234" @childFun="parentFun"></ChildPage>
</template>
<script setup>
import ChildPage from './ChildPage.vue';
import { ref } from 'vue';
var str = ref('11122334');
const parentFun = (e) => {
console.log('parentFun:', e);
};
</script>
对外界暴露组件实例
- 子组件
<script lang="ts" setup>
import { ref } from 'vue'
const a = 1
const b = ref('2')
defineExpose({
a,
b
})
</script>
- 父组件
<template>
<Child ref="refChild" />
<div @click="onClick">123</div>
</template>
<script lang="ts" setup>
import Child from './Child.vue'
const refChild = ref<any>(null)
function onClick () {
console.log(refChild.value) // { a: 1, b: '2' }
}
</script>
await也简单啦
- 在script setup下可以直接使用await
<script setup>
const post = await fetch(`/apiXXX`).then(res => {})
</script>
slots 和 attrs
<script lang="ts" setup>
import { useSlots, useAttrs } from 'vue'
const slots = useSlots()
const attrs = useAttrs()
</script>
欢迎大家指出文章需要改正之处~
学无止境,合作共赢
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决