簡體   English   中英

將外部JS對象輸入Vue.js組件

[英]Feed Outside JS object into Vue.js component

在我的JS中,有產品列表。

var productData = [{
    title: 'Bike',
    price: 300
},{
    title: 'Guitar',
    price: 199
}]

此數據是通過Async調用從遠程Json收集的。 因此,我必須在JS中執行此操作。

最終,我遇到了需要展示該產品的情況。 但是這里有兩件事。 1)在HTML中, 我不在主要的Vue實例范圍之內 之所以如此,是因為有第三方與這些產品進行交互的API,除了其他方面之外...因此,此數組不以任何方式綁定到Vue實例。 2)該產品列表是動態動態創建的。 為了顯示它,我必須做一個很好的舊html字符串連接,然后應用它。

主要問題 :現在,每當需要顯示產品時-我都有一個Vue.js組件。 那有一個模板,所有數據都運行得非常好。 我顯然想重用相同的模板。

所以現在我有這樣的事情:

//Vue.js Component, that I want to use, and feed my product to:
Vue.component('product', {
    props: ['product'],
    template: `
        <div class="prod">
            <h3>{{product.title}}</h3>
            <p>{{product.price}} €</p>
        </div>
`, data() {
        return {

        }
    }
});

接下來在JS中,我有以下代碼:

var prodList = getProductsAsync("3rd party service URL and parameters");
var prodHtml = '';
for(var i = 0; i < prodList.length; i++){
    prodHtml += `
        <div class="prod">
            <h3>${prodList[i].title}</h3>
            <p>${prodList[i].price} €</p>
        </div>
    `;
}

在這里,我有2個模板(一個作為JS html,另一個在Vue.js組件中),這是多余的。 我需要一種方法來維護此模板。 目前模板很簡單,但是不久就會有更多功能。

理想情況下,我希望我的JS對象使用我的Vue.js模板。 結果,它也將充當Vue.js組件。

因此,在我的JS中,我想要這樣(但是這顯然行不通):

var prodList = getProductsAsync("3rd party service URL and parameters");
var prodHtml = '';
for(var i = 0; i < prodList.length; i++){
    prodHtml += ` <product :product='prodList[i]'></product>`; // attempt to use Vue.js component 'on the fly' but this does not work!
}

有什么建議么?

它不起作用,因為必須按一定順序創建組件,html和Vue實例。

// just use all your code together
// first, prepare the component
Vue.component('product', {
  props: ['product'],
  template: `
    <div class="prod">
      <h3>{{product.title}}</h3>
      <p>{{product.price}} €</p>
    </div>
  `
})

// and get products
var prodList = getProductsAsync('/someMountpoint')

// then generate html with unknown tags "product"
var prodHtml = '<div id="productList">'
for(let i = 0; i < prodList.length; i++) {
  prodHtml += `<product :product='prodList[i]'></product>`
}
prodHtml += '</div>'

// append this html to DOM
$('#someWhere').html(prodHtml)

// and now create new Vue instance to replace
// these unknown product tags with real tags
new Vue({
  el: '#productList'
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM