文章目录
- hooks
- 目录结构
- demo
hooks
当页面内有很多的功能,js代码太多,不好维护,可以每个功能都有写一个js或者ts,这样的话,代码易读,并且容易维护,组合式setup写法与此结合👍👍🏼👍👍👍👍
目录结构
demo
- useDogs.ts
import { ref, reactive } from 'vue';
import axios from 'axios';
// https://dog.ceo/api/breed/pembroke/images/random
export default function () {
let dogList = reactive(['https://images.dog.ceo/breeds/pembroke/n02113023_1816.jpg']);
async function getDog() {
try {
let res = await axios.get('https://dog.ceo/api/breed/pembroke/images/random');
dogList.push(res.data.message);
console.log(res.data);
} catch (error) {
console.log(error);
}
}
return {dogList,getDog}
}
- useSum.ts
import { ref, reactive } from 'vue';
import axios from 'axios';
export default function () {
let sum = ref(0);
function add() {
sum.value += 1;
}
return {sum,add}
}
- 基本页面内容
<template>
<h2>当前求和为{{ sum }}</h2>
<button @click="add()">sum</button>
<button @click="getDog()">再来一只小狗</button>
<img v-for="dog in dogList" :src="dog" alt="" srcset="" /><br />
</template>
<script lang="ts" setup name="Hello321">
import useDogs from '@/hooks/useDogs';
import useSum from '@/hooks/useSum';
const { dogList, getDog } = useDogs();
const { sum, add } = useSum();
</script>