简体中文
目前 uni-app(Vue2) 基于 Vue 2.6,组合式 API 由 @vue/composition-api 支持,script setup 由 unplugin-vue2-script-setup 支持。
升级 uni-app 编译器到 3.6.8+
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()
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
}
}
})
npm install unplugin-vue2-script-setup -D
# or
yarn add unplugin-vue2-script-setup -D
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')
},
}
<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>
// vue.config.js
module.exports = {
chainWebpack (config) {
// disable type check and let `vue-tsc` handles it
config.plugins.delete('fork-ts-checker')
},
}