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>

欢迎大家指出文章需要改正之处~
学无止境,合作共赢
在这里插入图片描述

欢迎路过的小哥哥小姐姐们提出更好的意见哇~~

posted @   糖~豆豆  阅读(293)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
Live2D
欢迎阅读『Vue3的script setup语法糖这么好用的吗????』
点击右上角即可分享
微信分享提示