簡介
在開發手機端的H5 項目時,選擇了vue + vant生態,在使用PullRefresh 下拉刷新 組件時,需要進行自定義顯示。但是首頁Tab 下有3 個頁面都需要進行定制,為了方便將其封裝為一個組件。
源碼
下面是pullRefresh.vue 以及parent.vue 的相關源碼
1.子組件pullRefresh.vue
<template>
<van-pull-refresh v-model="isLoading" :head-height="80" @refresh="onRefresh">
<!-- 下拉提示,通過 scale 實現一個縮放效果 -->
<template #pulling="props">
<img
class="doge"
src="https://img.yzcdn.cn/vant/doge.png"
:style="{ transform: `scale(${props.distance / 80})` }"
/>
</template>
<!-- 釋放提示 -->
<template #loosing>
<img class="doge" src="https://img.yzcdn.cn/vant/doge.png" />
</template>
<!-- 加載提示 -->
<template #loading>
<img class="doge" src="https://img.yzcdn.cn/vant/doge-fire.jpg" />
</template>
<slot></slot>
</van-pull-refresh>
</template>
<script>
export default {
name: 'pull-refresh',
props: {
value: {
type: Boolean,
default: false,
}
},
data () {
return {
isLoading: false,
}
},
watch: {
value(val) {
// 3.1 偵聽到value 值改為true, 這時的val 為 true
// 7. 偵聽到父組件isLoading 值的改變,這是的val 為false
if (val == false) {
// 8. 由於val == false,此時子組件的isLoading 賦值為 false,完成下拉刷新過程
this.isLoading = false
}
}
},
methods: {
// 1. 子組件首次觸發onRefresh 事件
onRefresh () {
// 2. 更新父組件的value 的值,這里的value 在父組件中是isLoading
this.$emit('input', true)
// 4. 觸發父組件的refresh 事件,也就是父組件中的onRefresh 事件
this.$emit('refresh')
},
}
}
</script>
<style>
.doge {
width: 140px;
height: 72px;
margin-top: 8px;
border-radius: 4px;
}
</style>
2.父組件parent.vue
<tempalte>
<pull-refresh v-model="isLoading" @refresh="onRefresh">
父組件信息
</pull-refresh>
</template>
<script>
import pullRefresh from './pullRefresh.vue'
export default {
components: {
'pull-refresh': pullRefresh
},
data () {
return {
// 3.2 由於子組件中產生了input 事件,導致isLoading = true
isLoading: false,
}
},
methods: {
// 5. 子組件觸發了父組件中的onRefresh 方法
onRefresh () {
setTimeout(()=>{
// 6. 下拉刷新完成時,更新父組件的isLoading 為false,此時觸發了子組件中的value 的值改變
this.isLoading: false
}, 2000)
}
}
}
</script>
源碼解析
使用到的相關知識點:
過程分析
在頁面上模擬一次下拉刷新
- 子組件首次觸發onRefresh 事件
- 更新父組件的value 的值,這里的value 在父組件中是isLoading
- 此時會觸發兩次改變
3.1 偵聽到value 值改為true, 這時的val 為 true
3.2 由於子組件中產生了input 事件,導致isLoading = true - 觸發父組件的refresh 事件,也就是父組件中的onRefresh 事件
- 子組件觸發了父組件中的onRefresh 方法
- 下拉刷新完成時,更新父組件的isLoading 為false,此時觸發了子組件中的value 的值改變
- 偵聽到父組件isLoading 值的改變,這是的val 為false
- 由於val == false,此時子組件的isLoading 賦值為 false,完成下拉刷新過程
總結
項目中還是需要多看多寫多總結,這樣才能更好的理解Vue