掌握 Vue 3 的 <script setup>:高效开发的必备技巧

<script setup> 是 Vue 3 引入的一种新的 <script> 标记的用法,其本质是一个语法糖。它极大简化了单文件组件(SFC)的开发体验,目的是让代码更简洁、易读,同时减少模板和逻辑之间的重复。

1. 基本用法

<!-- 使用 <script setup> -->
<template>
  <div>
    <p>message: {{ message }}</p>
    <button @click="handleClick" style="margin-top: 10px; padding: 2px 6px;">点击我</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
// 定义响应式变量
const message = ref('Hello, Setup!');
// 定义一个方法
const handleClick = () => {
  message.value = '点击按钮!';
};
</script>
<!-- 使用之前的方式 -->
<template>
  <div>
    <p>message: {{ message }}</p>
    <button @click="handleClick" style="margin-top: 10px; padding: 2px 6px">点击我</button>
  </div>
</template>

<script>
import { ref } from 'vue'
export default {
  setup() {
    const message = ref('Hello, Setup!')
    const handleClick = () => {
      message.value = '点击按钮!'
    }
    return {
      message,
      handleClick
    }
  }
}
</script>

从这个简单的例子可以看出, <script setup> 让代码更加简洁易懂。

2. 特点

1、自动绑定上下文,简化导入和使用

在 <script setup> 中,所有的变量、函数、引入的库都自动绑定到模版的上下文中,无需显式返回,可以直接在模版中使用。

2、优化编译性能

<script setup> 在编译阶段进行了大量的优化,减少运行时开销。

3、更好的类型推断

当使用 TypeScript 时, <script setup> 让类型推断更加精确,开发体验更好。

<template>
  <div>
    <p>当前计数: {{ count }}</p>
    <button @click="increment">增加</button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
const count = ref<number>(0)
const increment = (): void => {
  count.value++
}
</script>

在 <script setup> 中加上 lang = 'ts',即表明这个文件是用 TypeScript 编写的,这样可以启用 TS 的类型检查和推断功能。 

3. 对比传统 <script> 

1、组件注册不需要手动处理,默认注册完成。

2、不需要使用 export default。

3、不需要使用 return 显式返回,<script setup> 最外层定义的对象、函数均自动返回,模版直接使用。

4、在 <script setup> 中,父组件拿不到子组件的实例成员,不能直接进行使用,这也是 vue 官方推荐的方法。可以使用 defineExpose 进行暴露,和原始样式的 expose 是一样。

<!-- 子组件 -->
<template>
  <div style="border: 1px solid pink;">
    <p>当前计数:{{ count }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
const count = ref(0)
const incrementCount = () => {
  count.value++
}
defineExpose({
  count,
  incrementCount
})
</script>
<!-- 父组件 -->
<template>
  <div class="container">
    <h2>父组件</h2>
    <MyComponent ref="MyComponentRef" />
    <button @click="childCount" class="btn">打印子组件的计数</button>
    <button @click="incrementChildCount" class="btn">增加子组件的计数</button>
  </div>
</template>

<script setup>
import MyComponent from './components/MyComponent.vue'
import { ref } from 'vue'

const MyComponentRef = ref(null)
const childCount = () => {
  console.log('访问子组件的 count: ', MyComponentRef.value.count)
}
const incrementChildCount = () => {
  MyComponentRef.value.incrementCount()
}
</script>

5、在 <script setup> 使用 defineProps 和 defineEmits。

举个 🌰

<template>
  <div style="border: 1px solid pink;">
    <h2>子组件</h2>
    <p>message:{{ message }}</p>
    <button @click="emitEvent" style="margin-top: 10px; padding: 2px 6px;">点击我</button>
  </div>
</template>

<script setup>
import { defineProps, defineEmits } from 'vue';

const props = defineProps({
  message: String
});
const emit = defineEmits(['customEvent']);
const emitEvent = () => {
  emit('customEvent', 'message from child');
};
</script>
<template>
  <div style="border: 1px solid red;">
    <h2>父组件</h2>
    <MyComponent :message="msg" @customEvent="handleCustomEvent" />
    <p>{{ receivedMessage }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import MyComponent from './components/MyComponent.vue';

const msg = ref('message from parent');
const receivedMessage = ref('');
const handleCustomEvent = (message) => {
  receivedMessage.value = `从子组件接收到的消息:${message}`;
};
</script>

4. 注意事项

1、单个 <script>

每个组件只能有一个 <script setup>,但可以同时使用 <script setup> 和 常规的 <script>,以兼容某些不支持的功能。

举个 🌰

<template>
  <div>
    <h3>Message from setup: {{ message }}</h3>
    <h3>Message from tradition script: {{ additionalMessage }}</h3>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
const message = ref('message from setup!')
onMounted(() => {
  console.log('这行代码运行在 script setup 的 onMounted 钩子中')
})
</script>

<script>
export default {
  name: 'MyComponent',
  data() {
    return {
      additionalMessage: 'message from traditional script!'
    }
  },
  mounted() {
    console.log('这行代码运行在 traditional script 的 mounted 钩子中');
  }
}
</script>

2、无法使用 this

在 <script setup> 中,没有组件实例上下文的概念,因此无法使用  this 访问组件的数据、方法或计算属性。所有状态和方法都是以局部变量的方式存在。

总结:

<script setup> 是 Vue 3 的一个强大特性,简化组件的编写方式,让 Vue 组件的开发更加高效和直观。对于开发者来说,可以大大提高开发效率和代码可维护性。

Vue 3中,`<script setup>`是一个新的语法糖,它可以更简洁地编写组件的逻辑部分。通过`<script setup>`,你可以在组件中使用Composition API,而无需显式地导入和使用`import { ... } from 'vue'`。 下面是使用`<script setup>`的基本用法: 1. 首先,在Vue 3的单文件组件中,将`<script>`标签替换为`<script setup>`。 2. 在`<script setup>`中,你可以直接使用Composition API提供的函数和响应式变量,无需显式导入。例如,你可以直接使用`ref`、`reactive`、`computed`等函数。 3. 在`<script setup>`中,你可以使用`defineProps`和`defineEmits`来定义组件的属性和事件。这样可以更方便地声明和使用组件的属性和事件。 4. 在`<script setup>`中,你可以使用`onXXX`的方式来定义组件的生命周期钩子函数。例如,你可以使用`onMounted`、`onUpdated`等函数。 下面是一个简单的示例,展示了如何使用`<script setup>`: ```vue <template> <div> <p>{{ count }}</p> <button @click="increment">Increment</button> </div> </template> <script setup> import { ref } from 'vue' const count = ref(0) function increment() { count.value++ } </script> ``` 在上面的示例中,我们使用了`<script setup>`来定义了一个计数器组件。通过`ref`函数创建了一个响应式变量`count`,并定义了一个`increment`函数来增加计数器的值。在模板中,我们直接使用了`count`变量和`increment`函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值