Vik*_*wal 5 javascript custom-controls web-component custom-element
大家好,我是 javaScript 的初学者,目前正在探索 JS Web 组件,但由于某些用例而陷入困境
1)我想将一个 JS 对象传递到我的组件中,例如
<my-component data=obj ></my-component>
Run Code Online (Sandbox Code Playgroud)
并要求在我的组件代码中使用
connectedCallback () {
console.log(this.data) // it should print {"name":"xyz" , "role" : "dev"}
}
Run Code Online (Sandbox Code Playgroud)
2)我还需要传递一些函数或者回调函数,比如。
function myFunction(e){
console.log(e)
}
<my-component click=myFunction ></my-component>
Run Code Online (Sandbox Code Playgroud)
请尝试在 ans 中添加代码片段,这将有助于我学习更多 JS。谢谢
您应该通过 Javascript 传递大对象。
通过自定义元素方法:
let comp = document.querySelector( 'my-component' )
comp.myMethod( obj )
Run Code Online (Sandbox Code Playgroud)
或者设置一个属性:
comp.data = obj
Run Code Online (Sandbox Code Playgroud)
小智 7
我和 Andreas Galster 一起上了一门 Udemy 课程,导师通过属性传入了一个 JSON 对象。
正如您所看到的,它还需要encodeURIComponent和decodeURIComponent来
attributeChangedCallback (name, oldValue, newValue) {
if (newValue && name === 'profile-data') {
this.profileData = JSON.parse(decodeURIComponent(newValue));
this.removeAttribute('profile-data');
}
this.render();
}
Run Code Online (Sandbox Code Playgroud)
传入:
<profile-card profile-data=${encodeURIComponent(JSON.stringify(profile))}>
</profile-card>
Run Code Online (Sandbox Code Playgroud)
该代码对我来说效果很好。
最好使用属性而不是属性来传递复杂数据。
myEl.data = {a:1,b:'two'};
Run Code Online (Sandbox Code Playgroud)
标准on事件在自定义元素上工作正常:
function myFunction(e){
alert(JSON.stringify(e.target.data));
e.target.data = {a:1,b:"two"};
}
class MyComponent extends HTMLElement {
constructor() {
super();
this._data = 0;
this.attachShadow({mode:'open'}).innerHTML="Click Me";
}
static get observedAttributes() {
return ['data'];
}
attributeChangedCallback(attrName, oldVal, newVal) {
if (oldVal !== newVal) {
}
}
get data() {
return this._data;
}
set data(newVal) {
this._data = newVal;
}
}
customElements.define('my-component', MyComponent);Run Code Online (Sandbox Code Playgroud)
<my-component onclick="myFunction(event)"></my-component>Run Code Online (Sandbox Code Playgroud)
如果您的组件调度自定义事件,那么最好通过代码访问它:
function specialEventHandler(evt) {
// do something
}
myEl.addEventListener('special-event;', specialEventHandler);
Run Code Online (Sandbox Code Playgroud)