亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

解決vue單頁面多個組件嵌套監聽瀏覽器窗口變化問題

瀏覽:77日期:2022-12-22 09:35:36

需求

最近公司有個大屏展示項目(如下圖)

解決vue單頁面多個組件嵌套監聽瀏覽器窗口變化問題

頁面的元素需要做響應式監聽,圖表需要跟著窗口響應變化

問題

每一個圖表都被我寫成了一個組件,然后就在每一個組件里寫了一串代碼,監聽瀏覽器變化

結果只有父組件的代碼生效

mounted(){ window.onresize = () => { //當窗口發生改變時觸發 // };}

原因

經簡單測試后發現,同一個路由頁面只能注冊一次瀏覽器窗口監聽事件,第二次注冊的會覆蓋第一次注冊

下邊代碼即可測試

mounted(){ window.onresize = () => { //當窗口發生改變時觸發 console.log(1) }; window.onresize = () => { //當窗口發生改變時觸發 (會覆蓋上一個函數) console.log(2) };}

父子嵌套組件同理,子組件生命周期執行在父組件之前,父組件函數會覆蓋子組件函數

解決方案

1、只在父頁面寫個監聽,但是通過組件傳值的方式傳給子組件,并且子組件用watch監聽傳值的變化,響應改變

2、假如是多層組件嵌套,用vuex可能會更省力

補充知識:vue/組件嵌套/無限嵌套/嵌套組件消息傳遞/嵌套父子組件傳值

目前接到一個需求,是我之前從來沒有實踐過的,正好趁此機會做一個深度剖析,并記錄下這次的成長,并分享給大家。

需求文檔

一 、(一個廠商編號和一個版本號)唯一決定一個配置

二 、 配置內容支持無限嵌套

三、配置數據格式示例(配置包括項和模塊):

{ 'vendorId': 'IL03#sub_01', 'version': '9.0.0', 'config': { 'module-1': { 'property-1': 'value-1', 'property-2': 'value-2', 'property-3': 'value-3', 'module-1_1': { 'property-1_1': 'value-1_1', 'property-1_2': 'value-1_2', 'property-1_3': 'value-1_3' } }, 'module-2': { 'property-4': 'value-4', 'property-5': 'value-5' } }}

四、配置成果物如下:

解決vue單頁面多個組件嵌套監聽瀏覽器窗口變化問題

需求分解

一個簡單的嵌套組件:

<template> <div> <span>{{data.content}}<span> <div> <nested :data='data.child'></nested> <div> </div></template><script>export default { name: ’nested’, props: [’data’]}</script>

我們給最外層的組件(根嵌套組件)綁定形如

{ 'content': 'value', 'child': { 'content': 'value-1' 'child': { 'content': 'value-1_1' ...... } }}

的數據結構,就可以看見效果了,是不是和我們前面需求的數據結構很像?

開始動工

step1:最外層列表展示

這里作為靜態路由頁面展示即可(分頁、查詢、刪除功能在這里做)

<!-- 這里使用了EL-UI --><template> <!-- 應用配置入口 --> <div class='app-config-wrap'> <!-- 增 --> <div class='app-config-add'> <el-button type='primary' size='mini' @click='handleClickAdd'>新增配置</el-button> </div> <!-- 查 --> <div class='app-config-search'> <div @click='isShowFilter = !isShowFilter'> <span class='text'>查詢App配置</span> <span v-if='!isShowFilter'></span> <span v-else></span> </div> <div @click='handleClearAll' v-if='isShowFilter'> <span class='text'>清空條件</span> </div> <div v-show='isShowFilter'> <div class='by-vendorId'> <el-input type='text' size='mini' placeholder='按廠商編號查詢' clearable v-model.trim='vendorId'> </el-input> </div> <div class='by-version'> <el-input type='text' size='mini' placeholder='按版本號查詢' clearable v-model.trim='version'> </el-input> </div> <div class='search-button'> <el-button type='primary' size='mini' @click='handleClickSearch'>查 詢</el-button> </div> </div> </div> <div :style='tableHeight'> <el-table size='mini' :data='configList' stripe @row-click='handleClickRow' highlight-current-row style='width: 100%;'> <el-table-column type='index' label='No.' width='60'></el-table-column> <el-table-column prop='vendorId' label='廠商編號' :show-overflow-tooltip='true'></el-table-column> <el-table-column prop='version' label='版本號' :show-overflow-tooltip='true'></el-table-column> <el-table-column prop='operation' label='操作'> <template slot-scope='scope'> <!-- 刪 --> <el-button type='danger' size='mini' @click='handleClickDelete(scope.row.id)'>刪除配置</el-button> </template> </el-table-column> </el-table> </div> <el-pagination v-if='total' background small :current-page='pageNum' :page-sizes='[10, 20, 40, 60]' :page-size='pageSize' layout='total, sizes, prev, pager, next, jumper' :total='parseInt(total)' @current-change='changePageNo' @size-change='changePageSize'> </el-pagination> </div></template><script>export default { name: ’appConfig’, components: {}, props: [], data () { return { isShowFilter: false, vendorId: ’’, version: ’’, pageNum: 1, pageSize: 20, total: 0, configList: [{ // 假數據 id: 1, vendorId: ’cjm’, version: ’10.0.0’ }] } }, computed: { tableHeight () { return this.isShowFilter ? { height: ’calc(100% - 129px)’ } : { height: ’calc(100% - 90px)’ } } }, methods: { handleClearAll () { this.vendorId = ’’ this.version = ’’ }, handleClickSearch () { // 這里發送查詢請求 }, changePageNo (val) { // 這里發送分頁請求 this.pageNum = val }, changePageSize (val) { // 這里發送分頁請求 this.pageSize = val }, handleClickDelete (id) { // 這里發送刪除請求 }, handleClickAdd () { // 使用路由方式跳轉到配置頁面(增加配置和修改配置同一頁面即可) this.$router.push({ name: ’configData’, query: {} }) }, handleClickRow (row) { // 通過id讓配置頁面初始化時請求數據,在跳轉頁面中watch即可 this.$router.push({ name: ’configData’, query: { id: row.id } }) } }}</script>// 樣式我就不貼了,節省篇幅

step2:動態路由頁準備

由于配置頁面展示是根據廠商編號和版本號動態改變的,所以這里用到

this.$router.push({ name: ’configData’, query: { id: row.id }})

來實現動態路由頁面,這里也需要引入我們的根嵌套組件(嵌套入口)。

<template> <div class='config-data-warp'> <div class='config-head'> <span class='text'>廠商編號:</span> <el-input type='text' size='mini' placeholder='廠商編號' clearable v-model.trim='vendorId'> </el-input> </div> <div class='config-head'> <span class='text'>版本號:</span> <el-input type='text' size='mini' placeholder='版本號' clearable v-model.trim='version'> </el-input> </div> <div class='config-main'> <config-module :data='config' :root='true' :commit='commit' @commit='handlerCommit'></config-module> </div> <el-button type='primary' size='mini' @click='commit = true'>確認提交</el-button> </div></template><script>import configModule from ’./configModule’export default { name: ’configData’, components: {configModule}, data () { return { id: this.$route.id, commit: false, vendorId: ’’, version: ’’, config: {} // 這里放點假數據 } }, mounted () { // 如果id存在,就去請求數據 if (id) { ... } }, methods: { handlerCommit (data) { // 這里是匯總數據的地方,記下來,等下提到了好找 console.log(data) this.commit = false } }}</script>

值得注意的是,確認提交按鈕只是將commit變量置為true,而commit綁定在我們的嵌套組件中。

<div v-for='(value, index) in configJsonChildren' :key='index + ’child’ + moduleName'> <config-module :index='index' @change='changeChildName' @commit='handlerCommit' :commit='commit' :data='{key: value[0], child: value[1]}'></config-module></div>

這是嵌套組件的部分代碼,我們可以看到commit被原封不動的傳遞給了子嵌套組件,也就是說,這里的commit變量起到通知所有嵌套組件執行了提交動作,這也是父組件控制子組件組件的唯一方式——傳遞數據變化props(或者使用vuex也可以)。

這里還有一點,就是定義什么是嵌套部分,什么是嵌套外部分,顯然,廠商編號和版本號不屬于嵌套部分。

還有傳入的root變量,是為了控制根嵌套組件的名稱不可修改,所以傳個true就可以了。

step3:嵌套組件的實現(重點)

這里梳理一下嵌套組件需要提供的功能點:

1、能夠做到傳入數據的展示

2、能夠動態添加項和模塊

3,能夠將修改了的數據傳遞出去

傳入數據的展示

我們再回過頭看看后臺傳給我們的數據格式:

{ 'vendorId': 'IL03#sub_01', 'version': '9.0.0', 'config': { 'module-1': { 'property-1': 'value-1', 'property-2': 'value-2', 'property-3': 'value-3', 'module-1_1': { 'property-1_1': 'value-1_1', 'property-1_2': 'value-1_2', 'property-1_3': 'value-1_3' } }, 'module-2': { 'property-4': 'value-4', 'property-5': 'value-5' } }}

從中我們是否可以提煉出每個嵌套組件的數據格式?

module: { property-1: value-1, property-2: value-2, ...... module-1: { ...... }, mpdule-2: { ...... }, ......}

而且,我們需要這個對象的key和value是可以被雙向綁定的。

可是我們想一下,對象的key可以雙向綁定嗎?顯然不能!

這也就是說,原始傳入的數據結構并不能用,需要進行處理:

<template> <div class='config-module-warp'> <div class='config-head'> <!-- 根組件固定模塊名,或者說不需要模塊名 --> <span v-if='root'>配置:</span> <div v-else> <el-input type='text' size='mini' placeholder='模塊名' clearable v-model='moduleName' @change='changeModuleName'></el-input> </div> <el-button type='primary' size='mini' @click='handleClickAddProperty'>新增項</el-button> <el-button type='primary' size='mini' @click='handleClickAddModule'>新增模塊</el-button> <el-button v-if='root' type='danger' size='mini' @click='handleClickClear'>清空配置</el-button> <el-button v-else type='danger' size='mini' @click='handleClickDeleteModule'>刪除模塊</el-button> <div v-for='(value, index) in configJsonProperty' :key='index + ’property’'> <el-input type='text' size='mini' placeholder='key' clearable v-model='value[0]'></el-input> : <el-input type='text' size='mini' placeholder='value' clearable v-model='value[1]'></el-input> <el-button type='danger' size='mini' @click='handleClickDeleteProperty(index)'>刪除該項</el-button> </div> <div v-for='(value, index) in configJsonChildren' :key='index + ’child’'> <config-module :index='index' @change='changeChildName' @commit='handlerCommit' :commit='commit' :data='{key: value[0], child: value[1]}'></config-module> </div> </div></template>...data () { return { moduleName: ’’, // 綁定當前子模塊名 configJsonProperty: [], // 這里是子模塊的property configJsonChildren: [], // 這里是子模塊下的子模塊(?I模塊^-^) ... }}...mounted () { if (this.data && this.root) { // 由于根節點是沒有模塊名的,數據的解析結構是{key: moduleName, child: moduleValue},參上。 this.classify({child: this.data}) } else if (this.data) { this.classify(this.data) }}// 或者將引用根組件的地方改成下面這樣也可以:// <config-module :data='{child: config}' :root='true' :commit='commit'// @commit='handlerCommit'></config-module>// _____________________________________// mounted () {// if (this.data) {// this.classify(this.data)// }// }...classify (prop) { let data = prop.child this.moduleName = prop.key for (let key in data) { if (typeof data[key] === ’object’) { this.configJsonChildren.push([ // 這里將數組轉化為可以雙向綁定的二維數組 key, data[key] ]) } else { this.configJsonProperty.push([ key, data[key] ]) } }}

實現動態增加

只需要添加空項就行了,但由于模塊是由父組件傳入的,所以改變模塊名也需要同步改變父組件的模塊名,而這里就用到了props中的index,代表父組件中的位置。

handleClickAddProperty () {this.configJsonProperty.push([ ’’, ’’ ])},handleClickAddModule () { this.configJsonChildren.push([ ’’, {} ])},changeModuleName (value) { this.$emit(’change’, this.index, value)},changeChildName (index, name) { this.$set(this.configJsonChildren[index], 0, name)},

孿生兄弟:動態刪除

其實,增加數據和刪除數據無外乎就是,本地數據本地改,外部數據同步改:

handleClickClear () { // 如果本身就是空,就無需操作,防止誤操作,畢竟我挺討厭彈窗的 if (!this.configJsonProperty.length && !this.configJsonChildren.length) { return } // 敏感操作給個彈窗 this.$confirm(’確定清空所有配置?’, ’警告’, { confirmButtonText: ’確定’, cancelButtonText: ’取消’, type: ’warning’ }).then(() => { // 這個是本地觸發的哦! this.configJsonProperty = [] this.configJsonChildren = [] })},handleClickDeleteProperty (index) { // 本地數據本地改 this.configJsonProperty.splice(index, 1)},handleClickDeleteModule () { // 外部數據傳出改,由于是刪除操作,外部銷毀了會直接導致本地銷毀,本地無需再銷毀 // 和改模塊名不一樣 // 改模塊名時,雖然外部數據改變觸發了本地更新,但由于是push操作,并不會改變本地數據 this.$emit(’delete’, this.index)},deleteModule (index) { // 與handleClickDeleteProperty方法比較,一定要分清哪個是子組件觸發,哪個是父組件觸發 this.configJsonChildren.splice(index, 1)},

重中之重:提取這個樹結構中的數據

數據在各個子組件中保存,怎么把它們提取出來呢?

聰明的你肯定馬上想到了我之前所說的commit變量吧,它將這個動作分發到了各個子組件。

所以,只要每個子組件聽從命令,把數據層層上報,是不是就完成了呢?

這就好比是公司總經理想要開發一個軟件,他就只要告訴各個部門:

哎,你們軟件部負責做出軟件可行性方案;

你們市場部負責調查同類軟件和市場份額;

你們營銷部趕快出爐軟件推廣方案,等等。

然后部門總監給各項目經理發小人物,然后項目經理再分解任務成需求給你。

最后做完了,流程就是:你 -》經理-》總監-》總經理。

在我們這份代碼中,也是這樣子的:

第一步:你要知道任務來了:

watch: { commit (val) { if (val) { this.handleClickCommit() // 接到任務 } else { this.commitData = {} // 這里也標記一下 } }},

第一步:找到最底層的“你”,也就是找到這個樹組件的末梢節點,

它的標志是:

if (!this.configJsonChildren.length) { ...... } // 他沒有子節點了

d收集它的“工作成果”:

let obj = {}this.configJsonProperty.forEach(v => { if (v[0] && v[1]) { obj[v[0]] = v[1] } else { this.$emit(’error’) // 如果有項不完整,可以報錯 }})

你覺得上面代碼有沒有小問題?給你五秒想一想。

1

2

3

4

5

有沒有這樣一種情況?我們一不注意寫了兩個同樣鍵名的項,不管是寫到了錯的模塊里面還是怎樣。

那么在上面的代碼中,就會使得新值覆蓋舊值,就有可能導致嚴重的事故!!!

所以我們改成:

handleClickCommit () { if (!this.configJsonChildren.length) { if (!this.moduleName && !this.root) { this.$emit(’error’) return } let obj = {} for (let v of this.configJsonProperty) { if (v[0] && v[1]) { if (obj.hasOwnProperty(v[0])) { this.$emit(’error’) // 啊,一不小心走神了 return } obj[v[0]] = v[1] } else { this.$emit(’error’) // 這里不需要return是因為不會造成嚴重后果,當然也可以加上 // 主要是我用這個功能時會一口氣添加好多項,也不一定全填滿,省得一個個刪。 } } this.$emit(’commit’, { // 把數據給經理!!!這個殺千刀的,天天催! key: this.moduleName, // 身份狗牌 value: obj }) }}

啊,工作終于提交了,再也不擔心了,接下來的事就交給經理去做吧!

經理:我手下管著這么多人,不可能來一個我上交一個吧?那就等他們全部上交了,我再整個打包上交吧。

首先第一步,我需要一個箱子來存他們的成果:

data () { return { moduleName: ’’, configJsonProperty: [], configJsonChildren: [], commitData: {} // 存放成果的箱子 }}

接下來就等他們上交了:

handlerCommit (data) { if (!this.moduleName && !this.root) { // 領導也要有名字,但總經理只有一個 this.$emit(’error’) return } this.commitData[data.key] = data.value // 先按人頭收下成果 for (let item of this.configJsonChildren) { if (!this.commitData.hasOwnProperty(item[0])) return // 如果沒收齊,繼續等待 } // 歐耶,收齊了 let obj = {} for (let v of this.configJsonProperty) { // 這個for循環可以封成一個函數的,畢竟寫了兩次 if (v[0] && v[1]) { if (obj.hasOwnProperty(v[0])) { this.$emit(’error’) return } obj[v[0]] = v[1] } else { this.$emit(’error’) } } this.$emit(’commit’, { key: this.moduleName, value: Object.assign(obj, this.commitData) // 領導自己的成果加上員工的成果 })}

還記得上面我讓你記下的地方嗎?

handlerCommit (data) { console.log(data) // 匯總數據,在這里可以發送給后臺了 this.commit = false // 任務完成標志}

watch: { commit (val) { if (val) { this.handleClickCommit() } else { this.commitData = {} // 初始化子組件 } }},

到這里,嵌套組件也大致完工了,貼全代碼:

<template> <div class='config-module-warp'> <div class='config-head'> <span v-if='root'>配置:</span> <div v-else> <el-input type='text' size='mini' placeholder='模塊名' clearable v-model='moduleName' @change='changeModuleName'></el-input> </div> <el-button type='primary' size='mini' @click='handleClickAddProperty'>新增項</el-button> <el-button type='primary' size='mini' @click='handleClickAddModule'>新增模塊</el-button> <el-button v-if='root' type='danger' size='mini' @click='handleClickClear'>清空配置</el-button> <el-button v-else type='danger' size='mini' @click='handleClickDeleteModule'>刪除模塊</el-button> </div> <div v-for='(value, index) in configJsonProperty' :key='index + ’property’'> <el-input type='text' size='mini' placeholder='key' clearable v-model='value[0]'></el-input> : <el-input type='text' size='mini' placeholder='value' clearable v-model='value[1]'></el-input> <el-button type='danger' size='mini' @click='handleClickDeleteProperty(index)'>刪除該項</el-button> </div> <div v-for='(value, index) in configJsonChildren' :key='index + ’child’'> <config-module :index='index' @change='changeChildName' @delete='deleteModule' @commit='handlerCommit' :commit='commit' :data='{key: value[0], child: value[1]}'></config-module> </div> </div></template><script>export default { name: ’configModule’, props: [’data’, ’root’, ’commit’, ’index’], data () { return { moduleName: ’’, configJsonProperty: [], configJsonChildren: [], commitData: {}, error: false } }, watch: { commit (val) { if (val) { this.handleClickCommit() } else { this.commitData = {} this.error = false } } }, computed: { }, mounted () { if (this.data) { this.classify(this.data) } }, methods: { classify (prop) { let data = prop.child this.moduleName = prop.key for (let key in data) { if (typeof data[key] === ’object’) { this.configJsonChildren.push([ key, data[key] ]) } else { this.configJsonProperty.push([ key, data[key] ]) } } }, handleClickAddProperty () { this.configJsonProperty.push([ ’’, ’’ ]) }, handleClickAddModule () { this.configJsonChildren.push([ ’’, {} ]) }, handleClickClear () { if (!this.configJsonProperty.length && !this.configJsonChildren.length) { return } this.$confirm(’確定清空所有配置?’, ’警告’, { confirmButtonText: ’確定’, cancelButtonText: ’取消’, type: ’warning’ }).then(() => { this.configJsonProperty = [] this.configJsonChildren = [] }) }, handleClickDeleteProperty (index) { this.configJsonProperty.splice(index, 1) }, handleClickDeleteModule () { this.$emit(’delete’, this.index) }, deleteModule (index) { this.configJsonChildren.splice(index, 1) }, changeModuleName (value) { this.$emit(’change’, this.index, value) }, changeChildName (index, name) { this.$set(this.configJsonChildren[index], 0, name) }, handleClickCommit () { if (!this.configJsonChildren.length) { if (!this.moduleName && !this.root) { this.$emit(’error’) return } let obj = {} for (let v of this.configJsonProperty) { if (v[0] && v[1]) { if (obj.hasOwnProperty(v[0])) { this.$emit(’error’) return } obj[v[0]] = v[1] } else { this.$emit(’error’) } } this.$emit(’commit’, { key: this.moduleName, value: obj }) } }, handlerCommit (data) { if (!this.moduleName && !this.root) { this.$emit(’error’) return } this.commitData[data.key] = data.value for (let item of this.configJsonChildren) { if (!this.commitData.hasOwnProperty(item[0])) return } let obj = {} for (let v of this.configJsonProperty) { if (v[0] && v[1]) { if (obj.hasOwnProperty(v[0])) { this.$emit(’error’) return } obj[v[0]] = v[1] } else { this.$emit(’error’) } } this.$emit(’commit’, { key: this.moduleName, value: Object.assign(obj, this.commitData) }) } }}</script>

總結

其實聰明的人根本就不需要我總結嘛,代碼是最好的語言

所以這里我提出一些我的不足和沒做完的部分,不過都是細枝末節啦:

第一個是錯誤的處理,我這邊沒有加上

第二個是模塊應該有折疊功能,不然配置多看著就眼花繚亂,

不過v-show的使用大家應該也是登峰造極了。

然后,大家有什么意見和建議都可以在下方反饋。

感謝大家看完這一篇長文,么么噠~希望能給大家一個參考,也希望大家多多支持好吧啦網

標簽: Vue
相關文章:
主站蜘蛛池模板: 日韩欧美精品综合一区二区三区 | 麻豆一区二区免费播放网站 | 欧美一级性 | www.黄色网.com| 欧美三级伦理片 | 久久精品这里精品 | 九九视频九九热 | 国产第一页在线观看 | 国产一区2区3区 | 黄色在线免费网站 | 久久国产精品高清一区二区三区 | 91制片厂制作果冻传媒麻豆 | 成人免费视频在线看 | 国产福利在线视频尤物tv | 护士一级aaaaaa毛片 | 欧美激情毛片 | 欧美一级黄色片免费看 | 五月婷婷俺也去开心 | 三极片免费看 | 亚洲成年人影院 | 黄色在线观看视频网站 | 91短视频版在线观看www免费 | 日韩亚洲一区中文字幕在线 | 国产亚洲欧美一区二区三区 | 动漫精品专区一区二区三区不卡 | 欧美5g影院天天5g天天看 | 69男女囗交动态图视频 | 国产精品视_精品国产免费 国产精品视频一区二区三区 | 网址黄| 深夜精品影院18以下勿进 | 亚洲欧洲国产成人综合一本 | 91在线精品你懂的免费 | 欧洲成品大片在线播放 | 成人一二 | 国产卡一卡二卡三 | 2020久久精品国产免费 | 久热中文字幕在线精品首页 | 国产精品偷伦视频免费观看的 | 在线观看永久免费 | 一区二区在线 | 高清国产亚洲va精品 |