S
S
Saint7392019-08-16 04:54:01
JavaScript
Saint739, 2019-08-16 04:54:01

How to make Vue run JavaScript loaded as text?

There is an old project that I don't really want to rewrite in a new way in terms of rendering. Yesterday I installed Vue router on it. The task is this - the API loads the content of the main block of the page in the form of html and JS,
after loading the content, you need to execute the loaded JS.
For convenience, here is an example of how I did it https://jsfiddle.net/oxg5mjwe/
In the example, through native JS, using eval, I can run the loaded JS, but how do I run it through Vue?
It's a big project to rewrite it correctly via json and components will take a very long time, so for now, in fact, I'm using the old rendering of the main window content issued by ROR on the server side.

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
  <div v-html="rendered_data"></div>
  <div id="novue">Без Vue</div>
</div>
<script>
const app = new Vue({

      data: {rendered_data: "", error: []},
      mounted: function() {this.load()},
      methods: {
        
        load: function() {
          
          axios.get("https://fiddle.jshell.net/k1wrdjsg/1/show/") 
          .then(res => {
            this.$root.rendered_data = res.data
            
            //если строку ниже раскомментировать то работает
            //document.getElementById('novue').innerHTML=res.data
            
            eval(document.getElementById('code').innerHTML);
          })
          .catch(e => {
            console.log(e)
            this.error.push(e)
          })
          
        }
        
      }
    }).$mount('#app')
</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
profesor08, 2019-08-16
@profesor08

Well, take it and see what you get in response. Separate the HTML from the JS, insert the html with the v-html directive, then execute your JS code with eval. All. If something doesn't work, then you're doing something wrong.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question