由于vue3.x还没有正式发布,所以可以通过安装包vue-function-api提前尝试
npm install vue-function-api --save
main.js
import Vue from 'vue'
import { plugin } from 'vue-function-api'
Vue.use(plugin)
test.vue
<template>
<div>
<span>{{msg}}</span><br>
<span>计算属性值:{{computedValue}}</span><br>
<el-button @click="appendName">点击</el-button>
</div>
</template>
<script>
import { value, computed, watch, onMounted, onUpdated, onUnmounted } from 'vue-function-api'
export default {
props: {
name: {
type: String
}
},
setup (props, context) {
/* eslint-disable no-alert, no-console */
const msg = value(2)
const msg2 = value(3)
console.log(context)
const appendName = () => {
msg.value += 1
msg2.value -= 2
}
const computedValue = computed(() => msg.value * 2)
watch([msg2, () => msg.value * 3], ([a, b]) => {
console.log(`a is: ${a}`)
console.log(`b is: ${b}`)
})
onMounted(() => {
console.log('mounted!')
})
onUpdated(() => {
console.log('updated!')
})
onUnmounted(() => {
console.log('unmounted!')
})
/* eslint-disable no-alert, no-console */
return {
msg,
appendName,
computedValue
}
}
}
</script>
参考链接:
https://github.com/vuejs/vue-function-api/blob/master/README.zh-CN.md
https://zhuanlan.zhihu.com/p/68477600