如何在GrapesJS中更改Dom组件中的类元素



我一直在寻找答案,现在想找到答案。所以问题来了:我需要更新一个GrapesDom元素的类名,这个元素是使用editor添加的。DomComponents.addType('myComponent'(。(在我使用的完整代码下面(

editor.DomComponents.addType('myComponent', {
isComponent: function (el) {
if (el.getAttribute && el.getAttribute('data-gjs-type') === 'myComponent') {
return {
type: 'myComponent'
}
}
},
model: containerModel.extend({
defaults: {
...containerModel.prototype.defaults,
tagName: 'div',
classes: ['container'],
traits: [
{
type: 'select',
name: 'default',
options: [
{ value: 'value_1', name: 'value 1' },
{ value: 'value_2', name: 'value 2' },
{ value: 'value_3', name: 'value 3' }
],
label: 'Défault'
}
],
editable: false,
stylable: false,
hoverable: false,
propagate: ['editable', 'stylable', 'hoverable', 'selectable'],
components: {
type: 'row',
classes: ['row'],
selectable: false,
propagate: ['editable', 'stylable', 'hoverable', 'selectable'],
components: {
type: 'column',
classes: ['col'],
components: myCustomComponent
}
}
},
init () {
this.on('change:attributes', this.handleChange);
},
handleChange () {
console.log('value ', this.getAttributes()) // This is working
// Here I would like to add a class name to an existing class of the component. Depending on the attribute, I'd like to change the position of 'active' class.
}
})
})

这是HTML myCustomComponent部分

<nav>
<div class="nav-1 active"> test 1 </div>
<div class="nav-2"> test 2 </div>
</nav>

有人知道怎么做吗?谢谢:(

如果有点晚了,很抱歉,但唯一缺少的是使用addClass方法添加active类。在这里你可以看到一个的工作示例

...
handleChange (attr) {
doSomething(attr);
if(something()) {
this.addClass('active')
}
}
...

注释

我看到您正在使用isComponent检查属性data-gjs-type是否是您类型的名称。您不需要这样做,因为如果已经设置了该属性,则方法isComponent将不会运行,并且将直接分配类型。

最新更新