ref
ref is a new api of vue3. Its meaning is to define a variable that can be "tracked" separately. All variables in data
need to be defined in 060d295b64e171, and a setup
field is added to vue3. Here we can be more flexible Define the variable .
vue3
export default defineComponent({
setup() {
const countA = ref(1);
return { count };
},
});
vue2
export default {
data() {
return { countA: 1 };
},
};
Someone may ask, what are the benefits of this new API of vue3?
The advantage is that the js business code can be split in more detail. For example, the countA
in the above example is the data returned by the interface. Generally, the interface must display a "loading animation" before the request is successful, this "loading animation" To show or hide requires a variable control, generally we call it isLoading
:
vue2
export default {
data() {
return { countA: 1, isLoading };
},
async mounted() {
this.isLoading = true;
const { data } = await axios.get('/api');
this.countA = data;
this.isLoading = false;
},
};
This is the way of writing vue2, I believe everyone wrote it like this, it seems that there should be nothing to continue encapsulating, right? Next, try to encapsulate ref
vue3
export default defineComponent({
setup() {
const [isLoading, countA] = useGet('/api');
return { isLoading, countA };
},
});
export function useGet(url) {
const isLoading = ref(true);
const dataSource = ref();
axios
.get(url)
.then(({ data }) => {
dataSource.value = data;
})
.finally(() => {
isLoading.value = false;
});
return [isLoading, dataSource];
}
The syntax of ref is not mentioned here, just know that isLoading.value=false
is isLoading
. For more information, please see vue official document
At this time, we found a scene that could not be abstracted, but now we can also abstract a useGet
, and the uncle number code is just 12 lines.
v-use-axios
Following the above ideas, I made a more complete package for , 160d295b64e36e v-use-axios , the code is not too logical or complicated, about 100 lines, I hope that interested friends can work with me to improve it.
WeChat group
Thank you for reading. If you have any questions, you can add me to WeChat. I will pull you into the WeChat group (Because Tencent has a limit of 200 people in WeChat groups, after 200 people must be pulled in by group members)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。