创建hook文件夹,和components同级,底下创建.js文件,以use开头,useCar.js导出一个函数
import { ref, computed } from "vue";
export default function () {
let carName = ref("奔驰");
let carPrice = ref(200000);
let updateCarName = (name) => {
carName.value = name;
}
let updateCarPrice = (price) => {
carPrice.value = price;
}
let usaCarPrice = computed(() => {
return '$' + (carPrice.value / (Math.random() + 6)).toFixed(2)
})
return {
carName,
carPrice,
updateCarPrice,
updateCarName,
usaCarPrice
};
}
导入useCar.js文件
import useCar from '../hooks/useCar.js'
export default {
name: "Child",
setup() {
return {
...useCar(),
...usePlane()
};
},
};
生命周期
vue2
beforeCreate() {
// 数据初始化前
},
created() {
//数据初始化完成
},
beforeMount() {
//数据初始化完成,页面未挂载前
},
mounted() {
//数据挂载页面完成
},
beforeUpdate() {
//数据修改后,页面数据重新挂载前
},
updated() {
//数据修改后,页面数据重新挂载完成
},
beforeDestroy() {
//数据销毁前
},
destroyed() {
// 数据销毁后
}
vue3
除了beforeCreate和created两个生命周期函数没有组合式API,因为setup函数充当了beforeCreate和created两个生命周期函数,其他的生命周期函数都有对应的组合式API,命名方式是在原有方法名前面加上on。
注意:setup是在beforeCreate和created两个生命周期函数之前运行的,所以在setup里面,无法调用data和methods里面的数据
<script>
import {ref,onBeforeMount,onMounted,onBeforeUpdate,onUpdated, onBeforeUnmount, onUnmounted } from 'vue'
export default {
name:'Child3',
setup() {
let count=ref(1)
let updateCount=()=>{
count.value++
}
onBeforeMount(() => {
//挂在前
console.log(onBeforeMount);
})
onMounted(() => {
//挂在完成
console.log(onMounted);
})
onBeforeUpdate(() => {
//修改后,页面重新挂载前
console.log(onBeforeUpdate);
})
onUpdated(() => {
//修改后,页面重新挂载完成
console.log(onUpdated);
})
onBeforeUnmount(() => {
//卸载前
console.log(onBeforeUnmount);
})
onUnmounted(() => {
//卸载完成
console.log(onUnmounted);
})
return{
count,updateCount ,onBeforeMount ,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted
}
}
}
</script>