Vue3 基础

156 阅读2分钟

ref()

ref()接受一个内部值,返回一个响应式的、可更改的 ref 对象,此对象只有一个指向其内部值的 property .value

import { ref } from 'vue'
const initCode = ref('20')
const user = ref({
  name:'hello vue3',
  age: 3
})

reactive()

reactive() 返回一个对象的响应式代理。

import { reactive } from 'vue'
const user = reactive({
  name: 'hello vue3',
  age:'20'
})
复制代码

computed ()

接受一个 getter 函数,返回一个只读的响应式 ref 对象,即 getter 函数的返回值。它也可以接受一个带有 getset 函数的对象来创建一个可写的 ref 对象。

// 只读
function computed(
  getter: () => {},
  debuggerOptions?: DebuggerOptions
)

// 可写的
function computed(
  options: {
    get: () => {}
    set: (value) => {}
  },
  debuggerOptions?: DebuggerOptions
)

computed()标注类型有两种方式:

import { ref, computed } from 'vue'
const count = ref(0)
const user = computed(() => {
  return 'hello vue3'
})

defineProps()

为了在声明 props 选项时获得完整的类型推断支持,我们可以使用 defineProps API,它将自动地在 script setup 中使用

const props = defineProps({
  name: { type: String, required: true },
  age: Number
})

通过对 defineProps() 的响应性解构来添加默认值:

<script setup>
const { name = 'hello vue3', age = 100 } = defineProps()
</script>

defineEmits()

为了在声明 emits 选项时获得完整的类型推断支持,我们可以使用 defineEmits API,它将自动地在 script setup 中使用

const emit = defineEmits(['say-hi', 'chang-name']);
// 调用 emit 打招呼
emit('say-hi', 'Hello!');
emit('chang-name', 'Tom!');

defineExpose()

defineExpose() 编译器宏来显式指定在 script setup 组件中要暴露出去的 property,使得父组件通过模板ref的方式获取到当前组件的实例

<script setup>
import { ref } from 'vue'

const name = ref('hello vue3')
defineExpose({
  name
})

provide()

provide()供给一个值,可以被后代组件注入

provide(name, 'hello vue3') 
复制代码

inject()

inject()注入一个由祖先组件或整个应用供给的值

// 没有默认值
function inject(key)
// 带有默认值
function injec(key, defaultValue)
const injectName = inject(name)

watch()

watch()侦听一个或多个响应式数据源,并在数据源变化时调用所给的回调函数。
侦听一个 ref:

const count = ref(0)
watch(count, (count, prevCount) => {
  /* ... */
})

当侦听多个来源时,回调函数接受两个数组,分别对应来源数组中的新值和旧值:

watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
  /* ... */
})

侦听一个 getter 函数:

const state = reactive({ count: 0 })
watch(
  () => state.count,
  (count, prevCount) => {
    /* ... */
  }
)

当直接侦听一个响应式对象时,侦听器会自动启用深层模式:

const state = reactive({ count: 0 })
watch(state, () => {
  /* 深层级变更状态所触发的回调 */
})

更新中。。。