简体   繁体   English

使用 vue.js 在其外部渲染组件模板

[英]Render component template outside it with vue.js

I have a template:我有一个模板:

var playersList = Vue.extend({
    props: ['players'],
    template: '#players-template'
});

Vue.component('players', playersList);

new Vue({
    el: 'body',
    methods: {
        someMethod: function() {
            //JSON data from request comes here
            //Want to render template of players component with that data
        }
    }
});

I'm new with Vue.js and don't know how could I make it possible.我是 Vue.js 的新手,不知道如何使它成为可能。 How can I render the template with data from AJAX request?如何使用来自 AJAX 请求的数据呈现模板? Someone posted a solution with v-view but documentation for it is gone at official website.有人用v-view发布了一个解决方案,但官方网站上没有相关文档。

You have to specify the data in your Vue instance where the response is going to be stored您必须在将要存储响应的 Vue 实例中指定数据

var playersList = Vue.extend({
    template: '#players-template',
    props: ['players']
    }
});

Vue.component('players', playersList);

new Vue({
    el: 'body',
    data: {
      players: ''
    },
    methods: {
        someMethod: function() {
            //JSON data from request comes here
            //Want to render template of players component with that data
            this.$set('players', data);
        }
    }
});

in your html
<body>
  <ul>
    <li v-for="player in players">
      <players :players="players"></players>
    </li>
  </ul>
<template id="players-template">
    <p>{{player.name}}</p>
</template>
</body>

Once you create the Vue app on the body element, you can use its component anywhere within that element.一旦你在body元素上创建了 Vue 应用程序,你就可以在该元素内的任何地方使用它的组件。 Since you named the component players, you'd render it like this:由于您命名了组件播放器,您可以像这样渲染它:

<body>
    <players :players="players"></players>
</body>

Then in your Vue然后在你的 Vue

new Vue({
el: 'body',
data: function(){
    return { players:[] }
},
methods: {
    someMethod: function() {
        //var result = ajax result
        this.players = result;
    }
}
});

Since players is a prop on your list component, you pass it in with :players="players" .由于players是列表组件上的道具,因此您可以使用:players="players"传递它。 Then if players updates on the parent app, the list component would automatically update according to the new list.然后,如果players在父应用上更新,列表组件将根据新列表自动更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM