由於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