首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Riot.js如何挂载预编译标记

Riot.js如何挂载预编译标记
EN

Stack Overflow用户
提问于 2021-08-05 16:37:47
回答 1查看 53关注 0票数 1

如何将已预编译的标记挂载到带有riot.js/cli的函数中,将其加载到iife版本。我做错了什么?因此获得一个空的html DOM。

代码语言:javascript
复制
<html> 
<head>

<script type="riot" src="/riot/tag.js"></script>
<script src="/js/riot.js"></script>
<script>
    riot.mount('tag');
</script>

</head>
<body>

    <tag></tag>

</body></html>

也许我还需要做些什么才能像函数风格一样挂载它呢?还试图先注册()。这似乎没什么用。也许我做错了?

代码语言:javascript
复制
riot.register('tag');
EN

回答 1

Stack Overflow用户

发布于 2022-04-28 15:02:39

你试过riot.inject()了吗?这是为了用于实时编译防暴组件,但我认为这是你错过的一步。

还请检查文档以获得更多上下文:https://riot.js.org/compiler/#in-browser-compilation-with-inline-templates

你已经编译好了,所以你不需要这个部分:

代码语言:javascript
复制
const tagString = document.getElementById('tag').innerHTML

// get the compiled code
const {code} = riot.compileFromString(tagString)

但是:您仍然需要获取位于/riot/tag.js链接文件中的已编译字符串,因此您必须以某种方式获取该字符串。如果您仍然想使用这种方法(现在是1/2年后的现在=D),我建议您将src属性更改为data-src (因此浏览器不会自动加载它,并自己处理已编译字符串的抓取,如下所示:

代码语言:javascript
复制
const el = document.getElementById('tag');
let response = await fetch(el.getAttribute('data-src'), {
    method: 'GET'
});

data = await response.text();

response = {
    headers: [...response.headers].reduce((acc, header) => {
        return {...acc, [header[0]]: header[1]};
    }, {}),
    status: response.status,
    data: data,
};

// create the riot component during runtime,
// response.data holds the compiled component code
riot.inject(response.data, 'tag', './tag.html')

下面是来自riot+compiler的函数供参考,它们比较简单:

代码语言:javascript
复制
// evaluates a compiled tag within the global context
function evaluate(js, url) {
  const node = document.createElement('script')
  const root = document.documentElement

  // make the source available in the "(no domain)" tab
  // of Chrome DevTools, with a .js extension
  if (url) node.text = `${js}\n//# sourceURL=${url}.js`

  root.appendChild(node)
  root.removeChild(node)
}

// cheap module transpilation
function transpile(code) {
  return `(function (global){${code}})(this)`.replace('export default', 'return')
}

function inject(code, tagName, url) {
  evaluate(`window.${GLOBAL_REGISTRY}['${tagName}'] = ${transpile(code)}`, url)
  riot.register(tagName, window[GLOBAL_REGISTRY][tagName])
}

function compileFromString(string, options) {
  return compiler.compile(string, options)
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68670417

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档