如何在模板 js 中将数据作为对象数组传递?

How to pass data as array of object in stencil js?

我一直在尝试将数据从 index.html 传递到 table-data 组件,但我得到的是未定义的。如果我在 table 数据标记中内联传递数据,它会起作用,但如果我明确传递,我会尝试很多方法,但我会变得不确定。

 index.html

       <table-data options="data"></table-data>

<script>
    var data = [ {name:'a', age: '25'}, {name:'b', age: '25'}, {name:'c', age: '25'}, {name:'d', age: '25'}];

</script>

table-data.tsx

@Component({
    tag: 'table-data',
    shadow: true
})

export class table-data{
    @Prop() options: string;
    @State() internalOptions: string[];

    componentWillLoad() {
        this.parseOptions();
    }

    @Watch('options')
    parseOptions() {
        if (this.options) {
            this.internalOptions = JSON.parse(this.options);
            console.log(this.internalOptions)
        }
    }
}

遗憾的是,您无法通过 html 属性传递“丰富”数据。为此,您应该使用 script 标签并将元素的 属性 分配为:

<table-data options="data"></table-data>

<script>
  const table = document.querySelector('table-data');
  table.options = [ {name:'a', age: '25'}, {name:'b', age: '25'}, {name:'c', age: '25'}, {name:'d', age: '25'}];
</script>

您也可以为属性使用字符串值,但稍后您需要 JSON.parse 它们。