Skip to content

Commit 2880428

Browse files
authored
Merge pull request #1636 from sveltejs/gh-875
use props when passing data to custom elements (#875)
2 parents 7b073bd + b26ee1c commit 2880428

File tree

5 files changed

+67
-3
lines changed

5 files changed

+67
-3
lines changed

src/compile/nodes/Attribute.ts

+5-3
Original file line numberDiff line numberDiff line change
@@ -130,9 +130,11 @@ export default class Attribute extends Node {
130130
// xlink is a special case... we could maybe extend this to generic
131131
// namespaced attributes but I'm not sure that's applicable in
132132
// HTML5?
133-
const method = name.slice(0, 6) === 'xlink:'
134-
? '@setXlinkAttribute'
135-
: '@setAttribute';
133+
const method = /-/.test(node.name)
134+
? '@setCustomElementData'
135+
: name.slice(0, 6) === 'xlink:'
136+
? '@setXlinkAttribute'
137+
: '@setAttribute';
136138

137139
const isLegacyInputType = this.compiler.options.legacy && name === 'type' && this.parent.name === 'input';
138140

src/shared/dom.js

+10
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,16 @@ export function setAttributes(node, attributes) {
9696
}
9797
}
9898

99+
export function setCustomElementData(node, prop, value) {
100+
if (prop in node) {
101+
node[prop] = value;
102+
} else if (value) {
103+
setAttribute(node, prop, value);
104+
} else {
105+
removeAttribute(node, prop);
106+
}
107+
}
108+
99109
export function removeAttribute(node, attribute) {
100110
node.removeAttribute(attribute);
101111
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<my-widget class="foo" {items}/>
2+
3+
<script>
4+
import './my-widget.html';
5+
6+
export default {
7+
tag: 'custom-element',
8+
9+
data() {
10+
return {
11+
items: ['a', 'b', 'c']
12+
};
13+
}
14+
};
15+
</script>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<p>{items.length} items</p>
2+
<p>{items.join(', ')}</p>
3+
4+
<script>
5+
export default {
6+
tag: 'my-widget',
7+
8+
data() {
9+
return {
10+
items: []
11+
};
12+
}
13+
};
14+
</script>
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import * as assert from 'assert';
2+
import CustomElement from './main.html';
3+
4+
export default function (target) {
5+
new CustomElement({
6+
target
7+
});
8+
9+
assert.equal(target.innerHTML, '<custom-element></custom-element>');
10+
11+
const el = target.querySelector('custom-element');
12+
const widget = el.shadowRoot.querySelector('my-widget');
13+
14+
const [p1, p2] = widget.shadowRoot.querySelectorAll('p');
15+
16+
assert.equal(p1.textContent, '3 items');
17+
assert.equal(p2.textContent, 'a, b, c');
18+
19+
el.items = ['d', 'e', 'f', 'g', 'h'];
20+
21+
assert.equal(p1.textContent, '5 items');
22+
assert.equal(p2.textContent, 'd, e, f, g, h');
23+
}

0 commit comments

Comments
 (0)