vue 开发一个按钮组件
生活随笔
收集整理的這篇文章主要介紹了
vue 开发一个按钮组件
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
最近面試,被問到一個(gè)題目,vue做一個(gè)按鈕組件;
當(dāng)時(shí)只是說了一下思路,回來就附上代碼。
解決思路:
通過父子組件通訊($refs 和 props) props接受參數(shù), $refs調(diào)用子組件的方法 來達(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.textthis.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>在頁面中調(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ú)寫一個(gè)并去掉scoped。總結(jié)
以上是生活随笔為你收集整理的vue 开发一个按钮组件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 人工智能云计算大数据物联网
- 下一篇: vue中的provide/inject的