我<span>的<template>.
<span ref="span-1">my text</span>
如何在我的部分中將其內容<span>從$refs更改my text為使用?我嘗試了以下所有兩個選項,但具有不同的屬性,例如,和,但沒有任何效果。my new text<script>innerHTMLinnerTexttext
this.$refs["span-" 1].span.value = "my new text";
this.$refs["span-" 1].value = "my new text";
當我使用.span時,我總是得到這個錯誤。
Uncaught TypeError: Cannot set properties of undefined (setting 'value')
如果我不使用.span,它只會為物件添加另一個屬性。如下圖所示,<span>元素的文本保持不變。

這是我的桌子:
<table class="table">
<thead>
<tr>
<th
v-for="(column, index) in columns"
v-bind:key="index"
v-on:click="sortRecords(index)"
>
{{column}} <span :ref="'span-' index"></span>
</th>
</tr>
</thead>
<tbody>
<tr
v-for="(row, index) in rows"
v-bind:key="index"
>
<td
v-for="(rowItem, itemIndex) in row"
v-bind:key="itemIndex"
>
{{rowItem}}
</td>
</tr>
</tbody>
</table>
這是我的功能
sortRecords (index) {
console.log(this.$refs);
if(this.sortIndex === index){
switch(this.sortDirection){
case null:
this.sortDirection = 'asc';
this.$refs["span-" index].textContent = "my new text";
break;
case 'asc':
this.sortDirection = 'desc';
this.$refs["span-" index].textContent = "my new text";
break;
case 'desc':
this.sortDirection = null;
this.$refs["span-" index].textContent = "my new text";
break;
}
}
}
編輯:我嘗試為.textContent<span>之外的測驗添加另一個測驗。v-for我還注意到,測驗跨度的物件$refs看起來與 for 回圈中創建的物件不同。該物件未顯示[]為另一個。你可以在下面的圖片中看到它。

uj5u.com熱心網友回復:
嘗試使用this.$refs["span-" 1][0].[textContent]` :
new Vue({
el: "#demo",
data() {
return{
columns: [1,2,3,4],
rows: [],
sortDirection: 'asc',
sortIndex: 1
}},
methods: {
sortRecords(index) {
if(this.sortIndex === index){
switch(this.sortDirection){
case null:
this.sortDirection = 'asc';
this.$refs["span-" index][0].textContent = "my new text";
break;
case 'asc':
this.sortDirection = 'desc';
this.$refs["span-" index][0].textContent = "my new text";
break;
case 'desc':
this.sortDirection = null;
this.$refs["span-" index][0].textContent = "my new text";
break;
}
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<table class="table">
<thead>
<tr>
<th
v-for="(column, index) in columns"
v-bind:key="index"
v-on:click="sortRecords(index)"
>
{{column}} <span :ref="'span-' index"></span>
</th>
</tr>
</thead>
<tbody>
<tr
v-for="(row, index) in rows"
v-bind:key="index"
>
<td
v-for="(rowItem, itemIndex) in row"
v-bind:key="itemIndex"
>
{{rowItem}}
</td>
</tr>
</tbody>
</table>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/510587.html
