繁体   English   中英

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

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

我有一个模板:

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
        }
    }
});

我是 Vue.js 的新手,不知道如何使它成为可能。 如何使用来自 AJAX 请求的数据呈现模板? 有人用v-view发布了一个解决方案,但官方网站上没有相关文档。

您必须在将要存储响应的 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>

一旦你在body元素上创建了 Vue 应用程序,你就可以在该元素内的任何地方使用它的组件。 由于您命名了组件播放器,您可以像这样渲染它:

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

然后在你的 Vue

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

由于players是列表组件上的道具,因此您可以使用:players="players"传递它。 然后,如果players在父应用上更新,列表组件将根据新列表自动更新。

暂无
暂无

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

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