vue2.0 如何自定义组件(vue组件的封装)
?
一、前言
??? 之前的博客聊過 vue2.0和react的技術選型;聊過vue的axios封裝和vuex使用。今天簡單聊聊 vue 組件的封裝。
??? vue 的ui框架現在是很多的,但是鑒于移動設備的復雜性,兼容性問題突出。像 Mint-UI 等說實話已經很不錯了,但是坑也是不少,而且項目中很多功能僅憑這些也實現不了,這需要我們去封裝自己的可復用組件。
?
二、封裝組件的步驟
1.? 建立組件的模板,先把架子搭起來,寫寫樣式,考慮好組件的基本邏輯。 os:思考1小時,碼碼10分鐘,程序猿的準則。
2.? 準備好組件的數據輸入。即分析好邏輯,定好 props 里面的數據、類型。(后面詳解)
3.? 準備好組件的數據輸出。即根據組件邏輯,做好要暴露出來的方法。(后面詳解)
4.? 封裝完畢了,直接調用即可。
?
? 接下來以一個很簡單的例子具體說明一下
? 現在先看一下demo的效果圖
?
三、代碼詳解
1. 先說一下 props
我們在父組件中需要將子組件需要的數據導入,用法如下:
<search @selectFunc="selectFunc" :searchList="searchList" :selectValue="selectValue"></search>:searchList="searchList"? 就是我們的數據,這個可以寫多個。這里我傳輸了2個參數過去,主要是做數據修改的說明。大家可以先忽略。
?
在子組件中,我們的接收和使用方法如下:
?
props: {searchList: Array,selectValue: Object}, mounted() {this.data = this.searchList},?
我們在 props 中接收數據,注意props對象里面 鍵值 是對改數據的 數據類型 的規定。做了規范,使用者就只能傳輸指定類型的數據,否則報警告
而props對象中的數據,我們可以直接在當前組件中使用 ?this.searchList,可以直接使用。這里要強調一下,props傳過來的數據只做展示,不得修改,想修改,再新寫一個data中的變量承接做數據的再處理。至于原因,同上,可以看一下js的原型。至于原理嘛,不懂的可以取腦補一下 js的原型 ?! s:這些基礎,在這就不做詳述了。
以上就是props傳遞過來的數據的使用了。
?
2. emit的使用(如何暴露組件方法)
我們已經會使用 父組件向子組件傳數據了,那如子組件如何來修改父組件的數據呢?
這里提供 2 種實現方法,但是 第一種不推薦,強烈不推薦
方式一:
?
?
selectValue: {data: '1'},。。。。。。。。。。。。。。。this.selectValue.data = '我被修改了'?
?
即,父組件將 對象 數據傳遞給子組件,子組件直接修改props過來的對象的值
可以實現,感覺是一個比較快捷的方式。但是不推薦,這種方式寫多了,容易出錯,特別是多層組件嵌套的時候。這種修改對代碼的迭代和錯誤的捕捉都不友好,所以建議大家別這樣寫。
他的實現原理簡單提一下: 這個對象、數組啦,是引用數據類型,說白了,就是存儲單元的信息是指針,真正數據在別的地方,通過指針查詢的數據,所以這樣寫,對瀏覽器來說僅僅是傳遞了一個指針,數據還是同一份數據。所以你能修改。
方式二:
正兒八經的通過 $emit 方法去掉父組件的方法,在父組件中修改data的數據。(根正苗紅的方法,規范寫法)
?
// 子組件 this.$emit('selectFunc', value) // 父組件 <search @selectFunc="selectFunc" :searchList="searchList" :selectValue="selectValue"></search>selectFunc(value) {this.selectValue2 = valueconsole.log(this.selectValue)console.log(this.selectValue2)}?
將父組件的方法注入子組件 ?@selectFunc="selectFunc" ,然后在子組件中通過 $emit 調用他,并傳遞參數。達到修改的目的。
?
四、 demo代碼
父組件:
?
<template><section class="f-mainPage"><!--selectFunc 選擇完成的回調 searchList 下拉列表的數據--><search @selectFunc="selectFunc" :searchList="searchList" :selectValue="selectValue"></search></section> </template><script type="text/ecmascript-6">import Search from '../vuePlugin/search'export default {data() {return {searchList: ['草船借箭', '大富翁', '測試數據'],// 直接通過props傳遞對象 修改,挺便捷的,但是不規范selectValue: {data: '1'},// 通過emit修改,規范寫法selectValue2: ''}},mounted() {},methods: {pageGo(path) {this.$router.push('/' + path)},selectFunc(value) {this.selectValue2 = valueconsole.log(this.selectValue)console.log(this.selectValue2)}},components: {Search}} </script><style lang="scss" scoped> .f-mainPage{width: 100%;.g-banner{width: 100%;background-image: url(../../../static/main_bg.png);background-repeat: no-repeat;background-size: 100% 100%;position: relative;overflow: hidden;color: white;text-align: center;p:nth-child(1) {margin: 10px auto 0px auto;font-size: 1.3rem;}.f-banscri {margin: 15px auto 8px auto;font-size: 0.95rem;}.f-moneyMax{margin: 5px auto 0px auto;font-size: 2.4rem;}.f-returnCash{width: 120px;height: 35px;text-align: center;line-height: 35px;background-color: white;color: #169BD5;display: inline-block;border-radius: 5px;font-size: 1rem;margin-top: 35px;position: relative;.f-mmmbd{position: absolute;width: 100%;height: 100%;background-color: transparent;top: 0;left: 0;}}}.g-cashInfor{width: 100%;text-align: center;display: flex;justify-content: space-between;div{width: 50%;height: 60px;line-height: 60px;box-sizing: border-box;}div:nth-child(1){border-bottom: 1px solid #878787;border-right: 1px solid #878787;}div:nth-child(2){border-bottom: 1px solid #878787;} }.g-operate{width: 100%;height: auto;overflow: hidden;ul{list-style: none;padding: 0;margin: 0;font-size: 1.05rem;li{height: 60px;line-height: 60px;padding-left: 25px;position: relative;span{width: 20px;height: 20px;position: absolute;top: 20px;right: 20px; background-image: url(../../../static/go.png);background-repeat: no-repeat;background-size: 100% 100%;}}}.f-goodNews{width: 340px;height: 144.5px;margin: 20px auto 30px auto;text-align: center;background-image: url(../../../static/banner.png);background-repeat: no-repeat;background-size: 100% 100%;}} } </style>?
子組件:
?
<template><div class="searchZJ"><div class="f-search"><div class="f-searchIn" v-bind:class="{searchInFous: this.fousFlag}">{{this.searchValue}}<span v-bind:class="{searchActive: this.searchFlag}" v-on:click="searchDown"></span></div><div class="f-searchXl" v-if="this.dataHas" v-bind:style="{height:this.searchFous, border:this.searchBorder}"><div v-for="item in searchList" v-on:click="choseValue(item)">{{item}}</div></div><div class="f-searchXl" v-else ><div>暫無數據</div></div></div></div> </template><script type="text/ecmascript-6">export default {data() {return {data: [],dataHas: true,searchFlag: false,searchFous: '0',fousFlag: false,searchValue: '',searchBorder: 'none'}},props: {searchList: Array,selectValue: Object},mounted() {this.data = this.searchList},methods: {searchDown() {this.searchFlag === false ? this.searchFlag = true : this.searchFlag = falsethis.searchFous === '0' ? this.searchFous = 'auto' : this.searchFous = '0'this.searchBorder === 'none' ? this.searchBorder = '1px solid #D9D9D9' : this.searchBorder = 'none'this.fousFlag === false ? this.fousFlag = true : this.fousFlag = false},choseValue(value) {this.searchValue = valuethis.searchDown()this.selectValue.data = '我被修改了'this.$emit('selectFunc', value)}}} </script><style scoped lang="stylus" rel="stylesheet/stylus">.f-search{width: 250px;height: auto;position: relative;margin-left: 20px;box-sizing: border-box;}.f-searchIn{width: 250px;height: 35px;line-height: 35px;font-size: 0.95rem;border-radius: 5px;overflow: hidden;position: relative;background-color: white;box-shadow: none;box-sizing: border-box;color: #000000;padding-left: 10px;border: 1px solid #A3A3A3;}.searchInFous{border: 1px solid #57C4F6;box-shadow: 0px 0px 5px #57C4F6;}.f-searchIn > span{display: block;width: 28px;height: 28px;background-image: url(../../../static/upDown.png);background-size: 100% 100%;background-repeat: no-repeat;background-position: 0px -13px;position: absolute;top: 10px;right: 5px;}.f-searchIn .searchActive{background-position: 0px 12px;top: -2px;}.f-search .f-searchXl{position: absolute;width: 100%;height: auto;max-height: 220px;top: 41px;left: -1px;border-radius: 5px;/*border: 1px solid #D9D9D9;*/background-color: white;overflow-x: hidden;overflow-y: scroll;}.f-search .f-searchXl > div{height: 35px;line-height: 38px;color: #000000;padding-left: 25px;font-size: 0.92rem;}.f-search .f-searchXl > div:hover{background-color: #D5F1FD;} </style>?
?
?
五、 總結
這里主要是總結一下vue組件封裝的思路,幫大家梳理一下。很簡單,和jQuery插件、react組件一樣,所有組件都是一個套路,就是 函數思想。
組件就是臺做烤腸的機器,我放進去豬肉,再按一下各種開關,然后你給我烤腸。
1. 定義好 你需要使用者傳入的數據
2. 定義好 你提供給使用者的方法
3. 寫好組件的內部邏輯
這就OK了,一個完美的,可復用的組件就完成了。??? os: 在此吐槽一下,那些自認為是優秀的組件,其實,別人拿著是沒法用的。 o(╥﹏╥)o?
os: 愿大家工作過程中能規范編程習慣,一起為前端代碼大社區做貢獻。
?
注:
? os:? 2018/06/06
鑒于一些朋友的評論,我在這再做一些解答哈,這個言論往深了去不保證準確性,我盡量吧。有問題的地方還是希望大家及時指出。
1.? 父子組件通信的方式,遠不止我說的那兩種。但是,通過 $emit 的方式是根正苗紅的,不帶任何差錯的,是封裝優秀組件最好的方式()
(1) 通過ref 通信
父組件設置ref,通過$refs對象來獲取子組件的數據
<search ref="refTest3" ></search> ....... console.log(this.$refs.refTest3) console.log(this.$refs.refTest3.selectValue.data)
?
? 其實,很簡單。ref 就是直接獲取了你的dom節點,如果是div一類的基本dom和js的document.getElementsByTagName()效果一樣的,而且這樣節省開銷。你可以在父組件中直接?this.$refs.refTest3.selectValue.data。直接獲取子組件data中的數據,或者別的數據都可以獲取。但是,這個不是我們封裝組件會用的東西,因為這個用在父組件。組件的思想是 獨立的。所以,大家平時用用就好了,如果要封裝可復用的組件,這個還是不實用的。? os:可能他有特殊用法是我不清楚的,如果有請大家分享
(2)通過 vuex 通信
vuex 大家都知道,變量統一管理(方便的很),╮(╯▽╰)╭? 但是用這個來封裝組件的完全就是抬杠了。vuex、redux等等這些都是針對組件多層傳輸數據不便,而做的狀態統一管理,說白了是針對大家都要用的數據才會放到vuex中,而組件思想,是封裝一個獨立的、可復用的功能模塊。這根本就是2個理念。希望大家不要被誤導。
?? (3).aync 父子組件數據雙向綁定
?
? 說實話,這也是來抬杠的。說白了,雙向綁定不還是 通過 ?$emit 監聽數據更新事件,來調用父組件的方法嗎?
這里簡單說一下這個數據雙向綁定的,還是很常用的方法。不啰嗦,看代碼:
<search @selectFunc="selectFunc" :syncTest.sync="syncTest"></search> ......... this.$emit('update:syncTest', value)其實,很簡單。在父組件向子組件props數據的時候,加一個 ?.sync? 修飾符,然后在子組件顯示的調用 emit 來修改他。 ? 說白了就是添加這樣的一個事件綁定? @update:foo="val => bar = val">
上述的方法就是? 父子組件數據雙向綁定。子組件實時修改? props 的方法。
?
歡迎大家提出別的問題和建議
總結
以上是生活随笔為你收集整理的vue2.0 如何自定义组件(vue组件的封装)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot笔记
- 下一篇: 前端学习(2681):重读vue电商网站