vue3 define 函数

定义 Options API 选项

vue3.3 引入了 defineOptions() 宏函数,用来定义 Options API 的选项,除了 props, emits, expose, slots (因为有对应 define 函数)

1
2
3
4
5
6
<script setup>
defineOptions({
    name: 'LoginIndex',
    // ...
})
</script>

name 的作用

  • 调试方便 - 在开发者组件会显示 name 的值
  • 递归组件 - 组件内部调用自己可以用自己的 name 的值
  • <keep-alive> 缓存可以用 name 决定是否缓存

父子组件双向绑定数据

原先为了实现双向绑定数据较为麻烦

父组件中

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<script setup>
import { ref } from 'vue';
import inputCom from './components/input-com.vue';

const msg = ref("a msg from father")
</script>

<template>
    <inputCom v-model="msg"></inputCom>
    <div>{{ msg }}</div>
</template>

子组件中

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<script setup>
defineProps({
    modelValue: String
})

const emit = defineEmits(['update:modelValue'])
</script>

<template>
    <div>
        <input
          type="text"
          :value="modelValue"
          @input="e => emit('update:modelValue', e.target.value)"></input>
    </div>
</template>

而使用了 defineModel() 函数后会更为方便,子组件可以写为

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<script setup>
const modelValue = defineModel()
</script>

<template>
    <div>
          <input
          type="text"
          :value="modelValue"
          @input="e => modelValue = e.target.value"></input>
    </div>
</template>
This post is licensed under CC BY-NC-SA 4.0 by the author.