認(rèn)識(shí)props
1.props是父組件傳遞給子組件的參數(shù)
2.props是只讀性的
3.props可以通過(guò)父組件傳遞給子組件自身的state的更新函數(shù)腮郊,然后子組件調(diào)用該更新函數(shù)實(shí)現(xiàn)子組件更新父組件數(shù)據(jù)
4.也可以實(shí)現(xiàn)一個(gè)類(lèi)似vue中的事件系統(tǒng)光督,子組件調(diào)用emit發(fā)出事件并攜帶參數(shù)蘸劈,父組件監(jiān)聽(tīng)改事件睬魂,接受參數(shù)與完成state更新操作碾阁。
簡(jiǎn)易事件系統(tǒng)代碼:
// eventProxy.js
const eventProxy = {
onObj: {},
oneObj: {},
on: function (key, fn) {
if (this.onObj[key] === undefined) {
this.onObj[key] = [];
}
this.onObj[key].push(fn);
},
once: function (key, fn) {
if (this.oneObj[key] === undefined) {
this.oneObj[key] = [];
}
this.oneObj[key].push(fn);
},
off: function (key) {
this.onObj[key] = [];
this.oneObj[key] = [];
},
emit: function () {
let key, args;
if (arguments.length === 0) {
return false;
}
key = arguments[0];
args = [].concat(Array.prototype.slice.call(arguments, 1));
if (this.onObj[key] !== undefined &&
this.onObj[key].length > 0) {
for (let i in this.onObj[key]) {
this.onObj[key][i].apply(null, args);
}
}
if (this.oneObj[key] !== undefined &&
this.oneObj[key].length > 0) {
for (let i in this.oneObj[key]) {
this.oneObj[key][i].apply(null, args);
this.oneObj[key][i] = undefined;
}
this.oneObj[key] = [];
}
}
};
export default eventProxy;
使用方法:
import eventProxy from './eventProxy.js'
eventProxy.emit('change','參數(shù)');
eventProxy.on('change', (params) => {
// 執(zhí)行邏輯
console.log(params)
})