Web Components, pass data to and from

前端 未结 4 1967
傲寒
傲寒 2020-12-23 20:35

My understanding is that data is passed to a custom html element via its attributes and sent out by dispatching a CustomEvent.

JavaScript objects can obviously be s

4条回答
  •  抹茶落季
    2020-12-23 21:21

    Passing Data In

    If you really want/need to pass large amounts of data into your component then you can do it four different ways:

    1) Use a property. This is the simplest since you just pass in the Object by giving the value to the element like this: el.data = myObj;

    2) Use an attribute. Personally I hate this way of doing it this way, but some frameworks require data to be passed in through attributes. This is similar to how you show in your question. . Be careful to follow the rules related to escaping attribute values. If you use this method you will need to use JSON.parse on your attribute and that may fail. It can also get very ugly in the HTML to have the massive amount of data showing in a attribute.

    3 Pass it in through child elements. Think of the