這個問題是在下在做一個 Vue 項目中遇到的實際場景,這里記錄一下我遇到問題之后的思考和最后怎么解決的(老年程序員記性不好 -。-),過程中會涉及到一些Vue源碼的概念比如 $mount、 render watcher等,如果不太了解的話可以瞅瞅 Vue源碼閱讀系列文章 ~
問題是這樣的:頁面從后台拿到的數據是由 0、 1之類的key,而這個key代表的value比如 0-女、 1-男的對應關系是要從另外一個數據字典接口拿到的;類似於這樣的Api:
{
"SEX_TYPE": [
{ "paramValue": 0, "paramDesc": "女" },
{ "paramValue": 1, "paramDesc": "男" }
]
}
那么如果view拿到的是 0,就要從字典中找到它的描述 女並且顯示出來;下面故事開始了~
1. 思考
有人說,這不是過濾器 filter 要做的事么,直接 Vue.filter 不就行了,然而問題是這個filter 是要等待異步的數據字典接口返回之后才能拿到,如果在 $mount 的時候這個filter沒有找到,那么就會導致錯誤影響之后的渲染(白屏並報 undefined錯);
我想到的解決方法有兩個:
把接口變為同步,在 beforeCreate或 created鈎子中同步地獲取數據字典接口,保證在 $mount的時候可以拿到注冊好的filter,保證時序,但是這樣會阻塞掛載,延長白屏時間,因此不推介;
把filter的注冊變為異步,在獲取filter之后通知 render watcher 更新自己,這樣可以利用vue自己的響應式化更新視圖,不會阻塞渲染,因此在下初步采用了這個方法。
2. 實現
因為filter屬於 assettypes ,關於在Vue實例中assettypes的訪問鏈有以下幾個結論;具體代碼實踐可以參考:Codepen - filter test
asset_types包括 filters、 components、 directives,以下所有的 asset_types都自行替換成前面幾項
子組件中的 asset_types訪問不到父組件中的 asset_types,但是可以訪問到全局注冊的掛載在 $root.$options.asset_types.__proto__上的 asset_types,這里對應源碼 src/core/util/options.js
全局注冊方法Vue.assettypes,比如Vue.filters注冊的assettypes會掛載到根實例(其他實例的 $root)的 $options.asset_types.__proto__上,並被以后所有創建的Vue實例繼承,也就是說,以后所有創建的Vue實例都可以訪問到
組件的slot的作用域僅限於它被定義的地方,也就是它被定義的組件中,訪問不到父組件的 asset_types,但是可以訪問到全局定義的 asset_types
同理,因為main.js中的 newVue()實例是根實例,它中注冊的 asset_types會被掛載在 $root.$options.asset_types上而不是 $root.$options.asset_types.__proto__上
根據以上幾個結論,可以着手coding了~
2.1 使用根組件的filters
因此首先我考慮的是把要注冊的filter掛載到根組件上,這樣其他組件通過訪問 $root可以拿到注冊的filter,這里的實現:
<template>
<div>
{{ rootFilters( sexVal )}}
</div>
</template>
<script type='text/javascript'>
import Vue from 'vue'
import { registerFilters } from 'utils/filters'
export default {
data() {
return {
sexVal: 1 // 性別
}
},
methods: {
/* 根組件上的過濾器 */
rootFilters(val, id = 'SEX_TYPE') {
const mth = this.$root.$options.filters[id]
return mth && mth(val) || val
}
},
created() {
// 把根組件中的filters響應式化
Vue.util.defineReactive(this.$root.$options, 'filters', this.$root.$options.filters)
},
mounted() {
registerFilters.call(this)
.then(data =>
// 這里獲取到數據字典的data
)
}
}
</script>
注冊filter的js
// utils/filters
import * as Api from 'api'
/**
* 獲取並注冊過濾器
* 注冊在$root.$options.filters上不是$root.$options.filters.__proto__上
* 注意這里的this是vue實例,需要用call或apply調用
* @returns {Promise}
*/
export function registerFilters() {
return Api.sysParams() // 獲取數據字典的Api,返回的是promise
.then(({ data }) => {
Object.keys(data).forEach(T =>
this.$set(this.$root.$options.filters, T, val => {
const tar = data[T].find(item => item['paramValue'] === val)
return tar['paramDesc'] || ''
})
)
return data
})
.catch(err => console.error(err, ' in utils/filters.js'))
}
這樣把根組件上的filters變為響應式化的,並且在渲染的時候因為在 rootFilters方法中訪問了已經在created中被響應式化的 $root.$options.filters,所以當異步獲取的數據被賦給 $root.$options.filters的時候,會觸發這個組件render watcher的重新渲染,這時候再獲取 rootFilters方法的時候就能取到filter了;
那這里為什么不用Vue.filter方法直接注冊呢,因為 Object.defineProperty不能監聽 __proto__上數據的變動,而全局Vue.filter是將過濾器注冊在了根組件 $root.$options.asset_types.__proto__上,因此其變動不能被響應。
這里的代碼可以進一步完善,但是這個方法存在一定的問題,首先這里使用了 Vue.util上不穩定的方法,另外在使用中到處可見 this.$root.$options這樣訪問vue實例內部屬性的情況,不太文明,讀起來也讓人困惑。
因此在這個項目做完等待測試的時候我思考了一下,誰說過濾器就一定放在filters里面 -。-,也可以使用mixin來實現嘛
2.2 使用 mixin
使用mixin要注意一點,因為vue中把data里所有以 _、 $開頭的變量都作為內部保留的變量,並不代理到當前實例上,因此直接 this._xx是無法訪問的,需要通過 this.$data._xx來訪問。
// mixins/sysParamsMixin.js
import * as Api from 'api'
export default {
data() {
return {
_filterFunc: null, // 過濾器函數
_sysParams: null, // 獲取數據字典
_sysParamsPromise: null // 獲取sysParams之后返回的Promise
}
},
methods: {
/* 注冊過濾器到_filterFunc中 */
_getSysParamsFunc() {
const { $data } = this
return $data._sysParamsPromise || ($data._sysParamsPromise = Api.sysParams()
.then(({ data }) => {
this.$data._sysParams = data
this.$data._filterFunc = {}
Object.keys(data).forEach(paramKey =>
this.$data._filterFunc[paramKey] = val => {
const tar = data[paramKey].find(item => item['paramValue'] === val)
return tar && tar['paramDesc'] || ''
})
return data
})
.catch(err => console.error(err, ' in src/mixins/sysParamsMixin.js')))
},
/* 按照鍵值獲取單個過濾器 */
_rootFilters(val, id = 'SEX_TYPE') {
const func = this.$data._filterFunc
const mth = func && func[id]
return mth && mth(val) || val
},
/* 獲取數據字典 */
_getSysParams() {
return this.$data._sysParams
}
}
}
這里把 Api的 promise 保存下來,如果其他地方還用到的話直接返回已經是 resolved狀態的 promise,就不用再次去請求數據了。另外為了在其他實例中也可以方便的訪問,這里掛載在根組件上。
那在我們的根組件中怎么使用呢:
// src/main.js
import sysParamsMixin from 'mixins/sysParamsMixin'
new Vue({
el: '#app',
mixins: [sysParamsMixin],
render: h => h(App),
})
在需要用過濾器的組件中:
<template>
<div>
{{ $root._rootFilters( sexVal )}}
</div>
</template>
<script type='text/javascript'>
export default {
data() {
return { sexVal: 1 }
},
mounted() {
this.$root._getSysParamsFunc()
.then(data =>
// 這里獲取到數據字典的data
)
}
}
</script>
這里不僅注冊了過濾器,而且也暴露了數據字典,以方便某些地方的列表顯示,畢竟這是實際項目中常見的場景。
當然如果使用 vuex 更好,不過這里的場景個人覺得沒必要用 vuex,如果還有更好的方法歡迎討論一下下啊~
❤️ 看完記得點贊喲