[Vuejs]-Vue.js v1 do not work properly with Ajax loaded html file

0👍

Alvaras,

I’m sending you example with one html file that I’m first pulling as template and then attaching vue instance.

I’ve used axios instead of jQuery, because it’s cool and I’ve included a bunch of code comments to help you understand what is happening.

Attention: only pull template files from servers that are fully trusted!

// let's start by pulling template file and callback our page logic
axios.get('https://dl.dropboxusercontent.com/s/4fg33iyn7kie88s/template.html')
  .then( function(res){
    // 1.) render our template on the page
    renderTemplate(res.data);
    // 2.) create Vue instance
    newVueInstance();
  })
  .catch( err );

// create template on our page
function renderTemplate(html){
  var el = document.createElement('div'); // create new 'div'
  document.body.append( el ); // append it to body
  el.innerHTML = html; // and set html
}

// attach new Vue fn
function newVueInstance(){
  // build new vue instance
  var list = new Vue({
    el:"#list",
    data: { items: [], type: 'posts', },
    methods: {
      // let's pull data from remote host (JSON format)
      pullData: function(verb) {
        var url = "https://jsonplaceholder.typicode.com/" + verb;
        axios.get( url )
          .then( function(res){
            list.items = res.data;
            list.type = verb;
          })
        .catch( err );
      },
    },
  });
}

// handle err
function err(er){ console.log( er );}
ul,
li {
  list-style: none;
  padding: 5px;
}

li .title,
a {
  font-weight: 900;
  cursor: pointer;
}
<script src="https://unpkg.com/axios@0.17.1/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue@2.5.8/dist/vue.min.js"></script>

Leave a comment