大家好,我有以下代码,我在其中查看json文件并将数据添加到表中。
我希望将product.refrencing_category_ids
中的数据输出到单独的行中,而不是像这样一行:
bc-men,bc-men-fashion,bc-men-underwear
我希望它看起来像:
bc-men,
bc-men-fashion,
bc-men-underwear
我该怎么做? product.refrencing_category_ids
是否需要另一个for循环?
我的代码如下:
<template>
<div>
<h1>Category Assignment</h1>
<table class="table">
<tr class="table-header">
<th>ID</th>
<th>Name</th>
<th>Primary category</th>
<th>Refrencing categories</th>
<th>Add</th>
<tr>
<tr class="product" v-for="product in products">
<td class="product__item"><input required type="text" v-model="product.id"></td>
<td class="product__item"><input required type="text" name="fname" v-model="product.name"></td>
<td class="product__item">
<input required type="text" name="fname" v-model="product.primary_category_id">
</td>
<td class="product__item">
<input required type="text" name="fname" v-model="product.refrencing_category_ids">
</td>
<td class="product__item">
<button v-on:click="product.quantity += 1">
Add
</button>
</td>
</tr>
</table>
<h2>Total inventory: {{ totalProducts }}</h2>
</div>
</template>
<script>
export default {
name: 'ProductEnrichment',
data () {
return {
products: [],
productHeadline: 'Product Flow Tool'
}
},
computed: {
totalProducts () {
return this.products.reduce((sum, product) => {
return sum + product.quantity
}, 0)
}
},
created () {
fetch('https://www.fennefoss.dk/product-request.json')
//fetch('./sample.json')
.then(response => response.json())
.then(json => {
this.products = json.products
})
}
}
</script>
答案 0 :(得分:0)
是,使用v-for
进入另一个循环。要使列表项具有反应性,您需要更新原始的data
而不是computed
。像这样:
new Vue({
el: '#app',
data() {
return {
product: {
refrencing_category_ids: 'bc-men,bc-men-fashion,bc-men-underwear'
}
}
},
methods: {
remove(idx) {
let items = this.product.refrencing_category_ids.split(',');
let removed = items.splice(idx, 1);
this.product.refrencing_category_ids = items.join(',');
}
},
computed: {
refCatIds() {
return this.product.refrencing_category_ids.split(',');
}
}
})
ul {
list-style: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li v-for="(id, index) in refCatIds" :key="index">
<a href="#" @click.prevent="remove(index)">{{id}}</a>
</li>
</ul>
</div>
答案 1 :(得分:-1)
用\n
(换行符)替换所有逗号
let string = "bc-men,bc-men-fashion,bc-men-underwear"
console.log(string.replace(/,/g, '\n'))