[英]How to use/link external api to show the fetched data in the grapejs component
我是grape和backbonejs的新手。我想制作一個模板構建器,它除了具有grapejs提供的默認組件,如label、圖像等,還將具有前5名產品的自定義組件,其中包含圖像和產品名稱以及它將從服務器獲取最新數據。 在這種情況下,我無法弄清楚應該在哪里進行 API 調用,以及如何使用獲取的結果在組件中顯示。 我嘗試過的代碼的鏈接在評論中。
如果您將代碼移動到道具更改處理程序,而不是視圖的 onRender function,您將能夠根據需要使用 API 調用中的值。
檢查這個小改動: https://jsfiddle.net/jvas28/8sb3tn94/1/
const editor = grapesjs.init({
container: '#gjs',
fromElement: 1,
height: '100%',
storageManager: { type: 0 },
});
editor.DomComponents.addType('test-component', {
model: {
defaults: {
testprop: '12345',
url: 'https://jsonplaceholder.typicode.com/posts/1'
},
init() {
console.log('Local hook: model.init', this.attributes.testprop);
fetch(this.attributes.url)
.then(response => response.json())
.then(commits => {
this.set('testprop', 'Test');
console.log(this.attributes.testprop);
});
this.listenTo(this, 'change:testprop', this.handlePropChange);
// Here we can listen global hooks with editor.on('...')
},
updated(property, value, prevValue) {
console.log('Local hook: model.updated',
'property', property, 'value', value, 'prevValue', prevValue);
},
removed() {
console.log('Local hook: model.removed');
},
handlePropChange() {
let prop = this.get('testprop');
// Here inside view it is getting the old value. of "testprop" i.e '12345' but not
//the new value
//which is being fetched from server in the init() of model.
let comp1 = '<div>' +
'<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png" />' +
'<span title="foo">' + prop + '</span>' + '</div>';
const component = editor.addComponents(comp1);
return component
}
},
view: {
init() {
console.log('Local hook: view.init');
},
},
});
// A block for the custom component
editor.BlockManager.add('test-component', {
label: 'Test Component',
content: `<div data-gjs-type="test-component"></div>`,
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.