前言
5月開始第二個vue項(xiàng)目炕泳,依舊是移動端昭殉,拿到效果圖后簡單的劃分了一下自己的任務(wù)模塊棵癣,計劃先封裝好公共組件和指令辕翰,然后再開始頁面編寫。
搭建項(xiàng)目
使用腳手架搭建項(xiàng)目狈谊,做完一些簡單的項(xiàng)目配置后喜命,在components里建一個public專門用來放置組件。
編寫組件
現(xiàn)在我們要寫一個小的switch開關(guān)組件:
我們希望把它做成一個單頁面的組件的畴,因?yàn)槲覀円ゾ庉嬎臉邮皆ǔ绽覀兿刃陆ㄒ粋€vue的文件components/public/mySwitch.vue,在里面去寫他的結(jié)構(gòu)和樣式丧裁,:
<style scoped>
.content{
display: inline-block;
}
.my-switch {
width: 52px;
height: 31px;
position: relative;
border: 1px solid #dfdfdf;
background-color: #fdfdfd;
box-shadow: #dfdfdf 0 0 0 0 inset;
border-radius: 20px;
background-clip: content-box;
display: inline-block;
-webkit-appearance: none;
user-select: none;
outline: none;
}
.my-switch:before {
content: '';
width: 29px;
height: 29px;
position: absolute;
top: 0;
left: 0;
border-radius: 20px;
background-color: #fff;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
}
.my-switch:checked {
border-color: #ff5208;
box-shadow: #ff5208 0 0 0 16px inset;
background-color: #ff5208;
}
.my-switch:checked:before {
left: 21px;
}
.my-switch.my-switch-animbg {
transition: background-color ease 0.4s;
}
.my-switch.my-switch-animbg:before {
transition: left 0.3s;
}
.my-switch.my-switch-animbg:checked {
box-shadow: #dfdfdf 0 0 0 0 inset;
background-color: #ff5208;
transition: border-color 0.4s, background-color ease 0.4s;
}
.my-switch.my-switch-animbg:checked:before {
transition: left 0.3s;
}
</style>
<template>
<div class="content">
<label>
<input class="my-switch my-switch-animbg" type="checkbox" :disabled="disabled" v-model="currentValue">
</label>
</div>
</template>
<script>
export default{
props: {
disabled: Boolean,
value: { // 你在外部通過v-model綁定的值在里面就寫成value
type: Boolean,
default: false
}
},
data () {
return {
currentValue: this.value
}
},
watch: {
currentValue (val) {
this.$emit('on-change', val)
},
value (val) {
this.currentValue = val
}
}
}
</script>
組件通信
我們知道在vue中护桦,父組件通過 props 向下傳遞數(shù)據(jù)給子組件,子組件通過 events 給父組件發(fā)送消息:
這里煎娇,我們的props里有兩個二庵,一個是在外部使用v-model綁定的value,一個是disabled,props可以設(shè)置:
type:值類型缓呛,
default:默認(rèn)值催享,
required:是否必須
現(xiàn)在,我們給組件內(nèi)部的checkbox使用v-model="currentValue"來監(jiān)聽他的值哟绊,并設(shè)置他的初始值為props傳進(jìn)來得值因妙,這樣我們的switch就能接受到外部傳進(jìn)來的值。
當(dāng)我們點(diǎn)擊時我們希望將checkbox的值傳出去票髓,這樣我們就要通過events去通信攀涵,在這里我們使用watch來監(jiān)測currentValue的值,當(dāng)他的值變化時洽沟,我們將events傳播出去并觸發(fā)以故。我們也監(jiān)測了value的值,當(dāng)value改變時將他值賦給currentValue用來顯示switch的開關(guān)狀態(tài)裆操,當(dāng)然怒详,如果在你寫的組件中需要用到點(diǎn)擊之類的,你也可以綁定click事件來觸發(fā)events踪区。
引入組件
然后我們在需要使用組件的地方將他import進(jìn)來昆烁,在components中注冊:
<div class="input-cloumn row gap">
<span>是否設(shè)置為默認(rèn)地址</span>
<iSwitch class="switch-default" v-model="isDefault" @on-change="setDefault"></iSwitch>
</div>
<script>
import iSwitch from "../public/switch.vue"
export default{
components:{
iSwitch
},
data(){
return{
isDefault: false
}
},
methods:{
setDefault(val){
this.isDefault = val;
console.log(this.isDefault)
}
}
}
</script>
ok,如果我們想禁用開關(guān)朽缴,只需要在組件上加上disabled就可以了善玫,現(xiàn)在可以看看我們的組件了,工作正常。
如有錯誤茅郎,請指出蜗元,感謝!