有兩種推薦的方法將數據存儲在A-Frame組件中,類似於公共和私有屬性。
架構(公衆)的組件的架構聲明
屬性是公共的,可以與setAttribute
設置以及帶getAttribute
和this.data.____
訪問。 注意:它是而不是安全地直接修改this.data
,因爲A-Frame將在接收來自DOM的更新時覆蓋數據。
HTML:
<a-entity foo="bar: 10"></a-entity>
JS:
AFRAME.registerComponent('foo', {
schema: {
bar: {default: 25}
},
init: function() {
console.log(this.data.bar); // 10
this.data.bar = 5; // THIS CHANGE MAY BE LOST.
},
doStuff: function() {
console.log(this.data.bar); // 10
this.el.setAttribute('bar', 'foo', 15);
console.log(this.data.bar); // 15
}
});
屬性(私人)
對於意在組件中使用的數據,你也可以直接將其分配到this
。當數據只在組件內使用時,這是最好的選擇,並且不需要在HTML中聲明。
JS:
AFRAME.registerComponent('foo', {
init: function() {
this.baz = 'hello';
console.log(this.baz); // hello
},
doStuff: function() {
console.log(this.baz); // hello
this.baz = 'bonjour';
console.log(this.baz); // bonjour
}
});
請分享你的代碼,所以它會更容易幫助您 –