1.没使用钩子前:
各种数据和方法都交织一起,组件易维护,代码复用性差,可读性差
<template>
<div class="job">
<h2>工资总计:{{ sum }}</h2>
<button @click="getSum">工资求和</button>
<h2>狗的照片:</h2>
<img v-for="(dog, index) in dogList" :src="dog" :key="index">
<br>
<button @click="getDogPhoto">获取狗的照片</button>
</div>
</template>
<script setup lang="ts" name="Job">
import { ref, reactive } from 'vue';
import axios from 'axios'
let sum = ref(12000)
let dogList = reactive([
'https://images.dog.ceo/breeds/pembroke/n02113023_1307.jpg'
])
function getSum() {
sum.value += 168
}
async function getDogPhoto() {
try {
let result = await axios.get('https://dog.ceo/api/breed/pembroke/images/random')
console.log(result.data)
dogList.push(result.data.message)
} catch (error) {
alert(error)
}
}
</script>
<style scoped>
.job {
background-color: aquamarine;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
img {
height: 100px;
margin: 5px;
}
</style>
2.hooks实战演练
完成页面:
![](https://i-blog.csdnimg.cn/direct/469b3be3ba614b64b24c0da0e8551f6b.png)
<template>
<div class="job">
<h2>工资总计:{{ sum }}</h2>
<button @click="getSum">工资求和</button>
<h2>狗的照片:</h2>
<img v-for="(dog, index) in dogList" :src="dog" :key="index">
<br>
<button @click="getDogPhoto">获取狗的照片</button>
</div>
</template>
<script setup lang="ts" name="Job">
import useSum from '@/hooks/useSum'
import useDog from '@/hooks/useDog'
const {sum,getSum} = useSum()
const {dogList,getDogPhoto} = useDog()
</script>
<style scoped>
.job {
background-color: aquamarine;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
img {
height: 100px;
margin: 5px;
}
</style>
钩子1:获取狗的照片
import { reactive } from 'vue';
import axios from 'axios'
export default function () {
let dogList = reactive([
'https://images.dog.ceo/breeds/pembroke/n02113023_1307.jpg'
])
async function getDogPhoto() {
try {
let result = await axios.get('https://dog.ceo/api/breed/pembroke/images/random')
console.log(result.data)
dogList.push(result.data.message)
} catch (error) {
alert(error)
}
}
return { dogList, getDogPhoto }
}
钩子2:求和
import { ref } from 'vue';
export default function () {
let sum = ref(12000)
function getSum() {
sum.value += 168
}
return { sum, getSum }
}