vue3.x 学习整理(一)__Vue.js
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利
作为菜鸟,第一次写点东西,有点小紧张,随便写写,有啥错误,请及时指正!
学习背景
最近领导指出下个项目使用vue3.x来做,一直听说vue3.x变化还挺大,该学习一下了,我一菜鸟没办法,我是被逼的,我发誓!
以下特性仅限于Composition Api 下:
一、生命周期对比
2.x生命周期
beforeCreate
created
beforeMount
mounted
beforeUpdate
updated
beforeDestroy
destroyed
3.x生命周期
beforeCreate、created生命周期没有了,onBeforeUnmount取代beforeDestroy,onUnmounted取代destroyed
onBeforeMount
onMounted
onBeforeUpdate
onUpdated
onBeforeUnmount
onUnmounted
二、setup函数介绍
setup是vue3新增的函数,为Composition Api的入口,所有生命周期函数,包括页面参数、方法都在其中书写;之后透过return向外暴露出来。如下:
export default {
name: 'Test',
components: {
},
setup() {
// 存放数据,常用于复杂数据类型
const state = reactive({
count: 0,
num: 0,
})
// 定义一些方法
const getData = () => {
console.log('初始化')
}
// 直接调用方法 类似于vue 2.x 中的 beforeCreate created 生命周期函数调用
getData()
// 存放数据,常用于简单数据类型
const num = ref(0)
// 页面点击事件函数
const addCount = () => {
state.count++
}
// 生命周期函数
onMounted(() => {
console.log('完成')
})
// 监听
watch(() => state.count, (newVal) => {
console.log(`count + num = ${newVal}`)
})
// 所有数据向外暴露展出
return {
...toRefs(state),
state,
num,
shiwo,
addCount,
addNum
}
}
}
略有些潦草,今天先这样吧,明天继续,加油!
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 作者: 前端婴幼儿 原文链接:https://juejin.im/post/6966871461642371085