微信店鋪小程序開發(fā)教程關(guān)鍵詞優(yōu)化價(jià)格
先看效果:
element-ui中的switch開關(guān)無(wú)loading屬性(在element-plus時(shí)加入了),而且點(diǎn)擊時(shí)開關(guān)狀態(tài)就會(huì)切換,這使得在需要調(diào)用接口后再改變開關(guān)狀態(tài)變得比較麻煩。
思路:switch開關(guān)外包一層div,給div添加click事件,emit給父組件,在父組件里進(jìn)行開關(guān)狀態(tài)的切換。
開關(guān)組件源碼:
<template><div class="custom-switch" @click="switchClick"><div style="width: fit-content;height: fit-content;" v-loading="loading"><el-switch style="position: relative;" v-bind="$attrs"></el-switch></div></div>
</template><script>
/*** el-switch開關(guān)組件二次封裝* * description:* 移除了el-switch的change事件* 添加了loading效果* 開關(guān)的value值交給父組件處理*/
export default {name: 'CustomSwitch',props: {loading: {default: false,type: Boolean}},data() {return {}},created() {},mounted() {},methods: {switchClick() {// 如果禁用和loading狀態(tài),不emit給父組件if (this.$attrs.disabled || this.loading) {return}this.$emit('switch-click', this.$attrs.value)}}
}
</script>
<style lang="scss" scoped>
.custom-switch {width: 100%;height: 100%;display: flex;align-items: center;justify-content: center;::v-deep .el-loading-mask {width: 100%;height: 100%;border-radius: 10px;top: 2px;.el-loading-spinner {position: relative;width: 100%;height: 100%;top: unset;margin-top: unset;display: flex;align-items: center;justify-content: center;svg {width: 20px;height: 20px;}}}
}
</style>
父組件:
<template><custom-switchv-model="switchValue":loading="switchLoading":active-value="1":inactive-value="0":disabled="switchDisabled"@switch-click="switchClick"/>
</template>
<script>
import CustomSwitch from './custom-switch.vue'export default {components: { CustomSwitch },data() {return {switchValue: 1,switchLoading: false,switchDisabled: false}},methods: {switchClick() {this.switchLoading = true// 這里就可以調(diào)用接口,接口成功后修改值和loading狀態(tài)setTimeout(() => {this.switchValue = !this.switchValue ? 1 : 0this.switchLoading = false}, 2000)}}
}
</script>