参考Vue3 Composition API 文档 composition-api.vuejs.org/zh/api.html…
setup
setup是最新的选项,可以理解是composition的入口,函数内部在beforeCreate之前调用,函数返回的内容会作为模板渲染的上下文。
setup() {
const state = reactive({
count: 1
})
function add() {
state.count++
}
const double = computed(() => state.count*2)
return { state, add, double }
}
Vue里需要用到的data、methods、computed全部是setup方法的return里面;不会像之前那样分开写了。
计算属性
const { computed } = Vue;
const App = {
setup() {
const state = reactive({
count: 0,
// computed()返回一个不可变的响应式引用对象
// 它封装了getter的返回值
doubleCount: computed(() => state.count * 2)
}) }
}
侦听器
const { watch } = Vue;
const App = {
setup() {
// state.count变化cb会执行
// 常用方式还有watch(()=>state.count, cb)
watch(() => {
console.log('count变了:' + state.count); })
} }
引用对象:单个原始值响应化
<div>counter: {{ counter }}</div>
const { ref } = Vue;
const App = {
setup() {
// 返回响应式的Ref对象
const counter = ref(1)
// 添加counter
return { statecounter }
} }
reactive
其实和Vue2里的Vue.observerable是一样的,把一个数据变成响应式,这个能力是完全独立的。reactive就是让数据响应式,和vue2中的data类似
import { reactive } from 'vue'
setup() {
const state = reactive({
hot: '',
common: '',
singer: {}
})
}
生命周期钩子
与Vue3中的大多数功能一样,生命周期钩子是我们必须导入到项目中的东西,这是为了帮助使项目尽可能轻巧。
我们导入生命周期钩子的方式是这样的。
import { onMounted, onUpdated, onUnmounted } from 'vue'
除去 beforeCreate 和 created 之外,在我们的 setup 方法中,有9个旧的生命周期钩子,我们可以在setup 方法中访问
- onBeforeMount
- onMounted
- onBeforeUpdate
- onUpdated
- onBeforeUnmount
- onUnmounted
- onActivated
- onDeactivated
- onErrorCaptured
这个方便的Vue2到Vue3的生命周期映射直接来自于Vue3 Composition API 文档,我认为这是一种最有用的方式来查看事情将如何变化,以及我们如何使用它们。
- beforeCreate -> use setup()
- created -> use setup()
- beforeMount -> onBeforeMount
- mounted -> onMounted
- beforeUpdate -> onBeforeUpdate
- updated -> onUpdated
- beforeDestroy -> onBeforeUnmount
- destroyed -> onUnmounted
- errorCaptured -> onErrorCaptured
新的调试钩子函数
们还可以在Vue3中使用两个全新的钩子函数来进行调试。他们是:
onRenderTracked
onRenderTriggered 这两个事件都带有一个DebuggerEvent,它使我们能够知道是什么导致了Vue实例中的重新渲染。
export default {
onRenderTriggered(e) {
debugger
// 检查哪个依赖项导致组件重新呈现
}
}