Vue3【十九】自定义Hooks钩子 将数据和方法分组
Vue3【十九】自定义Hooks钩子 将数据和方法分组
每个分组都可以放置 各种生命周期钩子
分组和可以使用计算属性等
案例截图
目录结构
代码
person.vue
<template><div class="person"><h2>Vue3自定义钩子Hooks</h2><h4> 求和结果: {{ sum }} ×10 = {{ bigSum }}</h4><button @click="add"> 点击 sum+1 </button><hr><button @click="getImg">增加一张图片</button><br><img v-for="(img,index) in imgLists" :src="img" :key="index" alt="" width="200px"></div>
</template><script lang="ts" setup namwe="Person">
import useImg from '@/hooks/useImg';
import useSum from '@/hooks/useSum';const { imgLists, getImg } = useImg();
const { sum, add, bigSum } = useSum();</script><style scoped>
.person {background-color: #ff9e4f;box-shadow: 0 0 10px;border-radius: 30px;padding: 30px;
}button {margin: 0 10px;padding: 0 5px;box-shadow: 0 0 5px;;
}
</style>
app.vue
<template><div class="app"><h1>你好世界! 我是App根组件</h1><Person /></div>
</template><script lang="ts" setup name="App">
import { ref } from 'vue';
import Person from './components/Person.vue'</script><style scoped>
.app {background-color: #4fffbb;box-shadow: 0 0 10px;border-radius: 10px;padding: 20px;
}
</style>
useImg.ts
import { onMounted, reactive } from 'vue';
import axios from 'axios'; // npm install axiosexport default () => {// 数据let imgLists = reactive([]);// 方法async function getImg() {try {let res = await axios.get('https://dog.ceo/api/breeds/image/random')console.log(res.data)imgLists.push(res.data.message)} catch (error) {alert(error)}}// 钩子 //页面一打开就来一张图片onMounted(() => {getImg()})// 提供给外部return {imgLists,getImg}
}
useSum.ts
import { computed, onMounted, ref } from 'vue';export default function () {// 数据let sum = ref(0);let bigSum = computed(() => {return sum.value * 10;});// 方法let add = () => {sum.value++;}//钩子 页面加载时候加100onMounted(() => {add();})// 提供给外部return {sum,add,bigSum}
}