A
A
Andrey Sobolev2020-11-21 10:10:30
HTML
Andrey Sobolev, 2020-11-21 10:10:30

How to force a script tag to execute from an API in VUE?

I have a component that gets content from an API. The content may include layout and a script with a map from the Yandex constructor.
For example:

<script type="text/javascript" charset="utf-8" src="//api-maps.yandex.ru/services/constructor/1.0/js/?sid=cmW8oHaPfpTIUddKnh6jsAZNzv8HxmaT&width=100%&height=450"></script>


Upon arrival in the component, all this content is rendered:
<template lang="pug">
div(v-html="сontent")
</template>


The problem is that the scripts that lie inside, namely Yandex maps, do not even run. In the Network block, there is not even a request for Yandex.
Here's how to make maps coming from the API render normally? Maybe someone faced such a problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-11-21
@andrufka46rus

The essence of the problem, as the documentation suggests :

HTML5 specifies that a <script>tag inserted with innerHTML should not execute .

So we will add the element scriptmanually. More precisely, we will replace the one that is with a new one with the same src.
Let's add a link to the element in which the html is written: Set a watch on the property containing the html string:
div(v-html="сontent" ref="content")
watch: {
  content() {
    this.$nextTick(() => {
      const oldScript = this.$refs.content.querySelector('script');
      const newScript = document.createElement('script');
      newScript.src = oldScript.src;
      oldScript.parentNode.replaceChild(newScript, oldScript);
    });
  },
},

https://jsfiddle.net/txk5zjLh/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question