vue3中composition API 的使用

1,495 阅读1分钟

写在前面

Vue3中Composition API用于公共逻辑的提取,提高复用性,在Vue2.0中我们可以使用mixins的方式提取一些公共处理逻辑。

为何使用Composition API

通常一个项目在长期的使用和维护,会累积了很多重复功能的代码以及变量,为了提高复用性,往往会将公用部分提取出来,以提高开发效率,节省时间。

本文中主要以公共方法和变量为例,简单的介绍一下composition API的使用。

如何设置Composition API

src下新建一个公共的文件目录,例如/src/options/useCommon.ts,在公共的文件中,定义好公用的变量和公用的方法并一起返回。

import { reactive ,getCurrentInstance } from '@vue/runtime-core';
export default function useCommon () {
  // 定义响应式数据
  const common = reactive({
    tableSizeFlag: false, //表格size控制flag
    loading: false, //表格数据加载中提示图标-默认为false,数据前为true,加载完修改为false-即接口请求执行完成后修改
    isShow: false, // 多行按钮的显示/隐藏
    moreConditions: false, // 更多事件的显示状态
  });
  const {proxy}:any = getCurrentInstance();
  // 公共方法
  function handleClose(done?:any) {
    proxy.moreConditions = false; //关闭更多条件
    proxy.$refs.table.doLayout();
  };
  // 将数据和方法返回
  return {
    common,
    handleClose,
  }
}

在vue文件中如何使用Composition API

  • script中引入定义好的方法
import { defineComponent, toRefs} from '@vue/runtime-core'; // 此处用vite搭建的项目
// import { defineComponent, toRefs} from 'vue'; // 默认
import useCommon from '@/options/useCommon';
  • setup中的解构并返回
export default defineComponent({
  setup(){
    const {common,handleClose} = useCommon();
    return {
      ...toRefs(common), // 用toRefs包裹才能是响应式数据
      handleClose,
    }
  },
})
  • 以上完成后就可在页面中使用公用的变量和方法了!