加载中...

Vue3 setup 方法的一些基本使用总结

官网介绍:https://cn.vuejs.org/api/composition-api-setup.html

基本使用

setup() 钩子是在组件中使用组合式 API 的入口,通常只在以下情况下使用:

  1. 需要在非单文件组件中使用组合式 API 时。
  2. 需要在基于选项式 API 的组件中集成基于组合式 API 的代码时。

setup方法返回值:

  1. 返回一个对象,对象中的属性和方法在模板中可以直接使用
import { ref } from 'vue'
const comTest = {
  setup() {
    const content = ref('chen')
    const updateContent = () => {
      content.value = 'nv'
    }
    return {     //setup返回一个对象,对象中的属性和方法将会被注入到组件实例中
      content,
      updateContent
    }
  }
}
  1. 返回渲染函数
    setup返回的函数为渲染函数,被用作组件的渲染。渲染函数返回了一个div,用于动态生成组件的内容。
setup(){
 
  return()=>{   //渲染函数
    return      //动态生成组件的内容
    <div class="left-side"></div>  
  }
}
  1. 返回模板中方法 + 渲染函数

返回一个渲染函数将会阻止我们返回其他东西。对于组件内部来说,这样没有问题,但如果我们想通过模板引用将这个组件的方法暴露给父组件,那就有问题了。

我们可以通过调用 expose() 解决这个问题:

import { h, ref } from 'vue'

export default {
  setup(props, { expose }) {
    const count = ref(0)
    const increment = () => ++count.value

    expose({
      increment
    })

    return () => h('div', count.value)
  }
}

使用 js/ts 文件写组件时使用

一般情况下,我们可以直接 export 一个对象出去,对象包含vue组件的各个属性和方法,也保护setup方法;但是为了写代码提示,我们可以使用 defineComponent 函数包裹一下这个对象; defineComponent 的唯一作用就是写代码有提示;

import { defineComponent } from 'vue'

export default defineComponent({
  name: 'TestCom',
  props: { },
  emits: [],
  setup(props, context) {
    ......
  }
})
posted @ 2023-12-13 12:09  水车  阅读(40)  评论(0编辑  收藏  举报