2

我正在尝试根据 API 调用的结果动态附加子 riot.js 标记。每当我尝试使用 jquery 的.append()函数附加这些标签时,DOM 都不会更新。我尝试了这个github线程上描述的以下方法(这对我不起作用):

https://github.com/riot/riot/issues/2279

var myTag = document.createElement('my-tag')
$('#container').append(myTag)
riot.mount(myTag)

这是我正在尝试做的一个简化示例(下面也列出了代码):https ://jsfiddle.net/7m2z7cus/12/

<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="https://rawgit.com/riot/riot/master/riot.min.js"></script>
  </head>
  <body>
    <foo></foo>
    <script>
      riot.tag('bar', '<h1>hello</h1>', '', '', function(opts) { });
      riot.tag('foo', '<div id="bars"></div>', '', '', function(opts) {
        var bar = document.createElement('bar');
        $('#bars').append(bar);
        riot.mount(bar);
      });
      riot.mount('foo');
    </script>
  </body>
</html>

我希望#barsdivbar附加一个标签,在屏幕上显示“Hello”,但它不存在。页面是空白的。我应该如何像上面的示例一样动态附加嵌套标签?

4

1 回答 1

2

您正在尝试做的事情是完全可能的,并且您的实施非常接近工作。

您唯一缺少的是标签foo需要完全安装,然后才能引用标签内的 DOM 节点,即如果没有完全安装,尝试引用$('#bars')将不会引用任何内容。foo

因此,为了使其正常工作,您需要在安装bar后创建并附加标签,foo这是通过使用'mount'标签的事件来完成的foo

<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="https://rawgit.com/riot/riot/master/riot.min.js"></script>
  </head>
  <body>
    <foo></foo>
    <script>
      riot.tag('bar', '<h1>hello</h1>', '', '', function(opts) { });
      riot.tag('foo', '<div id="bars"></div>', '', '', function(opts) {
        this.on('mount', function() {
          // foo has fully mounted. DOM Nodes are accessible inside this callback
          var bar = document.createElement('bar');
          $('#bars').append(bar);
          riot.mount('bar');
        })

      });
      riot.mount('foo');
  </script>
</body>

这是 JSFiddle:https ://jsfiddle.net/ypwwma2s/

于 2018-03-29T16:29:11.490 回答