簡體   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