国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > JavaScript > 正文

vue 開(kāi)發(fā)一個(gè)按鈕組件的示例代碼

2019-11-19 14:06:08
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

最近面試,被問(wèn)到一個(gè)題目,vue做一個(gè)按鈕組件;

當(dāng)時(shí)只是說(shuō)了一下思路,回來(lái)就附上代碼。

解決思路:

  1. 通過(guò)父子組件通訊($refs 和 props)
  2. props接受參數(shù), $refs調(diào)用子組件的方法
  3. 來(lái)達(dá)到點(diǎn)擊提交改變按鈕狀態(tài),如果不成功則取消按鈕狀態(tài)

在src/components/ 下建一個(gè)button.vue

<template><!-- use plane --><!-- 傳入bgColor改變按鈕背景色 --><!-- state切換button的狀態(tài) 調(diào)用cancel()可以切換 --><!-- text為按鈕文字 --> <div class="container">  <button    @click="confirm"   :disabled="state"    class="confirm"    :style="{background: btnData.bgColor}"  >{{text}}</button> </div></template><script>export default { data(){  return {   text: this.btnData.text,   state: false,  } }, props: {  btnData: {   types: Array,   default() {    return {     text: '確認(rèn)',    }   }  } }, methods: {  confirm(){   this.text += '...'   this.state = true   //這里是激活父組件的事件,因?yàn)樽咏M件是不會(huì)冒泡到父組件上的,必須手動(dòng)調(diào)用$emit   //相對(duì)應(yīng)父組件要在調(diào)用該組件的時(shí)候,將其掛載到上面   this.$emit("confirm")  },  cancel(){   this.text = this.btnData.text   this.state = false  } }}</script><style lang="less" scoped>.confirm { border: none; color: #fff; width: 100%; padding: 1rem 0; border-radius: 4px; font-size: 1.6rem; background: #5da1fd; &:focus {  outline: none; }}</style>

在頁(yè)面中調(diào)用:

<template>  <div class="btn-box">   <Btn     :btnData="{text: '確認(rèn)注冊(cè)'}"    <!--這里就要掛載$emit調(diào)用的事件 @confirm="想要調(diào)用事件的名字"-->    @confirm="confirm"    ref="btn"   ></Btn>  </div> </template><script>import Btn from '@/components/button'export default { components: {  Btn }, methods: {  confirm(){   if(!this.companyName){    this.$toast("公司名不能為空")     this.$refs.btn.cancel()   } }}</script>

在這里,要注意一些細(xì)節(jié):

1. button組件形成之后和其它div元素的間距,如果是在組件內(nèi)定死是很難復(fù)用的。

2. 在復(fù)用的時(shí)候,在父組件中是改變不了子組件的樣式的,如果要強(qiáng)制更改,單獨(dú)寫(xiě)一個(gè)并去掉scoped。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 开原市| 辉南县| 正阳县| 阜宁县| 鲁甸县| 蒙城县| 松阳县| 建昌县| 尼玛县| 齐河县| 河曲县| 阿尔山市| 安平县| 宁强县| 翁源县| 澄江县| 台东市| 永泰县| 广昌县| 阳东县| 新田县| 新宁县| 都江堰市| 鄂温| 大理市| 息烽县| 桓台县| 西丰县| 延长县| 徐闻县| 龙游县| 瑞丽市| 马公市| 辽中县| 武隆县| 陵川县| 宜城市| 邹平县| 桐梓县| 雷州市| 鄂托克旗|