Vue.js v1 无法与 Ajax 加载的 html 文件一起正常工作

Vue.js v1 do not work properly with Ajax loaded html file

我有一个与通过 ajax 请求加载的内容相关的小问题。

我正在创建一个 Web 应用程序,所有内容都在一个页面上,无需任何重新加载或其他操作即可运行。所以我将内容部分划分为单独的文件,并将其加载到 Ajax.

如果我将所有内容加载到一个文件中而不划分为单独的文件,一切正常。但是当我制作内容文件并开始通过 Ajax jQuery 请求加载它时,Vue.js 停止与 {{variable}} 或其他事件一起正常工作。

我正在使用 Vue.js v1,并且 jQuery 用于此网络应用程序。

感谢您的回答。

阿尔瓦拉斯,

我正在向您发送示例,其中包含一个 html 文件,我首先将其作为模板拉取,然后附加 vue 实例。

我使用 axios 而不是 jQuery,因为它很酷,而且我包含了一堆代码注释来帮助您理解正在发生的事情。

注意:只从完全信任的服务器中提取模板文件!

// 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>