# 组合式 API(Composition API)

Currently uni-app (Vue2) is based on Vue 2.6, the composition API is supported by @vue/composition-api, script setup is supported by unplugin-vue2-script-setup support.

# Environment preparation

升级 uni-app 编译器到 3.6.8+

# Using the Composition API

  1. Add and install the @vue/composition-api plugin in the main.js/ts file. If you use the nvue page, you also need to install it on each nvue page, and the plug-in state will not be shared between each nvue page by default.

main.js

composition-api.js

pages/index/index.nvue

import './composition-api'
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

const app = new (typeof App === 'function' ? App : Vue.extend(Object.assign({ mpType: 'app' }, App)))
app.$mount()
  1. 从 @vue/composition-api 包内导入并使用基础的组合式API,具体的兼容性仍需参考:@vue/composition-api。从 @dcloudio/uni-app 包内导入 uni-app 应用生命周期页面的生命周期
import { defineComponent, ref } from '@vue/composition-api'
import { onReady } from '@dcloudio/uni-app'
export default defineComponent({
  setup(_, { expose }) {
    const title = ref('Hello')
    onReady(() => {
      console.log('onReady')
    })
    // @vue/composition-api 当前版本并无 expose 方法
    if (expose) {
      expose({
        title
      }) 
    }
    return {
      title
    }
  }
})

# Using Script Setup

  1. Use npm/yarn to install the unplugin-vue2-script-setup plugin. This plugin does not support nvue pages at the moment.
npm install unplugin-vue2-script-setup -D
# or
yarn add unplugin-vue2-script-setup -D
  1. Configure the ScriptSetup plugin in vue.config.js. The following is the basic configuration. For other specific configurations, please refer to unplugin-vue2-script-setup
const ScriptSetup = require('unplugin-vue2-script-setup/webpack').default
module.exports = {
  parallel: false,
  configureWebpack: {
    plugins: [
      ScriptSetup({ /* options */ }),
    ],
  },
  chainWebpack (config) {
    // disable type check and let `vue-tsc` handles it
    config.plugins.delete('fork-ts-checker')
  },
}
  1. Use Script Setup to import API
<script setup>
import { ref } from '@vue/composition-api'
import { onReady } from '@dcloudio/uni-app'
const title = ref('Hello')
onReady(() => {
  console.log('onReady')
})
defineExpose({
  // 注意要在 defineExpose 函数外定义
  title
})
</script>

# Working with TypesScript

  • 与 Script Setup 一同使用时会禁用默认的类型检查,具体请参考 unplugin-vue2-script-setup
  • 即使不与 Script Setup 一同使用但项目为 HBuilderX 创建的工程时,由于 HBuilderX 内置TypesSript插件当前版本较低,也需要禁用默认的类型检查
  // vue.config.js
  module.exports = {
    chainWebpack (config) {
      // disable type check and let `vue-tsc` handles it
      config.plugins.delete('fork-ts-checker')
    },
  }