我正在努力为这个问题找到解决方案:我正在使用Vue.js和Laravel 5.6并获取项目,然后使用Vue显示它们。
点击对此商品的出价按钮时,我想更新其中的数据< li>列表项,例如使用 bidOnThis(id)方法 ref 属性 totalBids 的元素
已编辑更新了代码,以反映参考属性以及更新但仍然错误的 bidOnThis(id)功能
<template>
<div>
<ul class="row">
<li class="col-lg-4" v-for="auction in auctions" :key="auction.id">
<span>{{ auction.name }} {{ auction.id }}</span><br />
<span>{{ auction.bid_time }}</span><br />
<span ref="totalBids">{{ auction.total_bids }}</span><br />
<span ref="user">{{ auction.username }}</span><br />
<button ref="newBid" @click="bidOnThis(auction.id)">Bid on this item</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
auctions: [],
newBid: '',
totalBids: ''
};
},
created() {
axios.get('/auctions').then(result => {
this.auctions = result.data
})
},
methods: {
bidOnThis(id) {
axios.post('/auctions', { id: id });
this.auction.totalBids = '100';
}
}
};
这就是我所处的位置,但是无法正常工作
bidOnThis(id) {
axios.post('/auctions', { id: id });
this.auctions.$refs.totalBids.innerHTML = '100';
}
答案 0 :(得分:1)
经过大量的搜索,我找到了这个:Better method of using refs inside a v-for based on object
并在我的v-for循环中使用键,索引更新了我的代码,然后通过该方法引用键 允许我使用键来引用正确的元素
bidOnThis(auction.id, key)
和
this.$refs.totalBids[key].innerHTML = parseInt(this.$refs.totalBids[key].innerHTML) + 1 ;
请参阅下面的完整代码:
<template>
<div>
<h1 ref="testing">0</h1>
<ul class="row">
<li class="col-lg-4" v-for="(auction, key, index) in auctions" :key="auction.id">
<span>{{ auction.name }} ({{ auction.id }})</span><br />
<span>{{ auction.bid_time }}</span><br />
<span ref="totalBids">{{ auction.total_bids }}</span><br />
<span ref="user">{{ auction.username }}</span><br />
<button ref="newBid" @click="bidOnThis(auction.id, key)">Bid on this item</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
auctions: [],
newBid: '',
totalBids: '',
testing: ''
};
},
created() {
axios.get('/auctions').then(result => {
this.auctions = result.data
})
},
methods: {
bidOnThis(id, key) {
axios.post('/auctions', { id: id });
this.$refs.totalBids[key].innerHTML = parseInt(this.$refs.totalBids[key].innerHTML) + 1 ;
}
}
};