Dynamically add items to an mdl menu

2019-09-03 06:41发布

问题:

I want to dynamically add menu items to an mdl menu. However, I have not figured out how to register the new items with mdl so that they work properly.

Here is a codepen showing the different behavior. Notably, the dynamic item does not have a ripple effect, or close the menu on click.

That code pen uses componentHandler.upgradeElement on both the newly created item, and the original menu element to no effect. I've noticed that the properly created menu items also have another class (mdl-js-ripple-effect) in addition to some other attributes, but manually adding that class, or trying to futz with element data resulted in a lot of errors in the mdl javascript. I assume that a few proper calls to componentHandler methods is all I need, but I haven't been able to find any documentation on its proper use with subelements.

回答1:

This sadly is currently pretty complicated and doing it will in fact have performance issues due to bugs. Not recommended.

The best thing to do would be to destroy the menu and rebuild it on-the-fly.

MDL is meant for more static sites, Polymer is recommended for sites needing more complex controls and dynamic building.

You could also go the route of not using our JS and writing your own component for this need.