最近面試,被問到一個題目,vue做一個按鈕組件;
當時只是說了一下思路,回來就附上代碼。
解決思路:
通過父子組件通訊($refs 和 props)
props接受參數, $refs調用子組件的方法
來達到點擊提交改變按鈕狀態,如果不成功則取消按鈕狀態
在src/components/ 下建一個button.vue
<template> <!-- use plane --> <!-- 傳入bgColor改變按鈕背景色 --> <!-- state切換button的狀態 調用cancel()可以切換 --> <!-- text為按鈕文字 --> <p class="container"> <button @click="confirm" :disabled="state" class="confirm" :style="{background: btnData.bgColor}" >{{text}}</button> </p> </template> <script> export default { data(){ return { text: this.btnData.text, state: false, } }, props: { btnData: { types: Array, default() { return { text: '確認', } } } }, methods: { confirm(){ this.text += '...' this.state = true //這里是激活父組件的事件,因為子組件是不會冒泡到父組件上的,必須手動調用$emit //相對應父組件要在調用該組件的時候,將其掛載到上面 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>
在頁面中調用:
<template> <p class="btn-box"> <Btn :btnData="{text: '確認注冊'}" <!--這里就要掛載$emit調用的事件 @confirm="想要調用事件的名字"--> @confirm="confirm" ref="btn" ></Btn> </p> </template> <script> import Btn from '@/components/button' export default { components: { Btn }, methods: { confirm(){ if(!this.companyName){ this.$toast("公司名不能為空") this.$refs.btn.cancel() } } } </script>
在這里,要注意一些細節:
1. button組件形成之后和其它p元素的間距,如果是在組件內定死是很難復用的。
2. 在復用的時候,在父組件中是改變不了子組件的樣式的,如果要強制更改,單獨寫一個并去掉scoped。
相信看了本文案例你已經掌握了方法,更多精彩請關注Gxl網其它相關文章!
推薦閱讀:
JS左邊列表轉移右邊
微信小程序分享頁面后跳轉回首頁
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com