Vue composable 共用組件 v-if用法 及 axios
composable 共用組件,官方建議 依照use開頭
比如 今天要做一個監聽滑鼠位置的程式
const pageX = ref(0);
const pageY = ref(0);
const mouseposition = (e) => {
pageX = e.pageX;
pageY = e.pageY;
}
onMounted(() => { //這代表生命週期 他只會在程式載入時第一次執行
windows.addEventListener("mousemove " , mouseposition ); //註冊一個mousemove的事件 回傳值丟到mouseposition中
} )
onUnmounted(() => { //這也是代表生命週期 這會在關閉畫面的時候執行 類似C#的資源回收
windows.removeEventListener("mousemove " , mouseposition );
} )
然後把這些東西丟進composiable內
並且使用 export function functionname(){
return {
PageX ,
PageY};
} 包住
並且引入的方法就是
import { functionName } from "./yoursite/yourFunctionName"
這跟之前不一樣 要括號
然後引用方法
const {PageX , PageY} = functionName
實作一個function
import {ref , readonly } from "vue"
export function useAddData(val){
const data = ref(val);
const setData = (data) => {
data.value = data
}
return {
data : readonly(data), //這樣會限制data 不能被外部更改 只能由函式 setData
setData ,
}
}//這樣是輸出data 跟 setData Function
//在其他頁面import後
<script>
import {useAddData} from "檔案位置"
const {data , setData } = useAddData(0); //這個0等於val
<template>
<button @click="setData(data++)"> //這個data = data setData 是那個function
// 番外 使用 axios 的話
import axios from "axios";
export function useaxios(){
const data = ref(null);
const errormsg = ref("");
const fetchInit = async () => {
try {
const res = await axios get("url")
data.value = res.data;
}catch (error){
}
}
return {data , errormsg , fetchInit}
}
//番外 v-if
<template>
<div v-if="條件1">
//todo
</div>
<div v-if="條件二">
//todo
</div>
參考:Vue3 + Vite 快速上手 Get Startrd EP5
留言
張貼留言