Vue-组合式函数

81 阅读2分钟

1、setup

  1. <script setup> 是在单文件组件 (SFC) 中使用组合式 API 的编译时语法糖。当同时使用 SFC 与组合式 API 时该语法是默认推荐。相比于普通的 <script> 语法,它具有更多优势:
  • 更少的样板内容,更简洁的代码。
  • 能够使用纯 TypeScript 声明 props 和自定义事件。
  • 更好的运行时性能 (其模板会被编译成同一作用域内的渲染函数,避免了渲染上下文代理对象)。
  • 更好的 IDE 类型推导性能 (减少了语言服务器从代码中抽取类型的工作)。
  • 更好的类型推断:由于 setup() 函数中的代码是在编译时执行的,而不是在运行时执行的,因此 TypeScript 能够更好地推断出组件的类型信息,从而提供更好的类型检查和错误提示。
  • 更好的性能优化setup() 函数中的代码执行时机是在组件实例创建之前
  • 与普通的 <script> 只在组件被首次引入的时候执行一次不同,<script setup> 中的代码会在每次组件实例被创建的时候执行

1.1 、顶层的绑定会被暴露给模板

<script setup>
// 变量
const msg = 'Hello!'
import { capitalize } from './helpers'

// 函数
function log() {
  console.log(msg)
}
</script>

<template>
  <button @click="log">{{ msg }}</button>
  <div>{{ capitalize('hello') }}</div>
</template>
  1. 可以在模板表达式中直接使用导入的 helper 函数,而不需要通过 methods 选项来暴露它。

2、动态组件

  1. <component :is="currentComponent"></component>
  2. 根据:is 的值判断显示哪个组件
<template>
  <div>
    <button @click="currentComponent = 'Home'">Home</button>
    <button @click="currentComponent = 'About'">About</button>
    <component :is="currentComponent"></component>
  </div>
</template>

<script>
import Home from './components/Home.vue';
import About from './components/About.vue';

export default {
  components: {
    Home,
    About
  },
  data() {
    return {
      currentComponent: 'Home'
    };
  }
};
</script>

3、命名空间组件

<script setup>
import * as Form from './form-components'
</script>

<template>
  <Form.Input>
    <Form.Label>label</Form.Label>
  </Form.Input>
</template>

举例

src/
|-- components/
|   |-- Form/
|   |   |-- Input.vue
|   |   |-- Select.vue
|   |-- UI/
|       |-- Button.vue
|       |-- Modal.vue

<template>
  <div>
    <Form.Input />
    <UI.Button />
  </div>
</template>

<script setup>
import Form from '@/components/Form/Input.vue';
import UI from '@/components/UI/Button.vue';
</script>

4、自定义指令

<template>
  <div>
    <input v-my-upper-directive />
    <p v-my-upper-directive>This text will be converted to uppercase</p>
  </div>
</template>

<script setup>
const vMyUpperDirective= {
  mounted(el) {
    el.addEventListener('input', () => {
      el.value = el.value.toUpperCase();
    });
  }
};
</script>
  1. 在 Vue 自定义指令中,el 是指令绑定的目标元素,即指令所作用的 DOM 元素。在 mounted 钩子函数中,el 参数表示指令所绑定的 DOM 元素。
  2. 上面代码中el 表示使用自定义指令的元素,例如 <input v-uppercase /><p v-uppercase> 中的 <input><p> 元素。在这个例子中,el 将分别指向这两个元素。