VueJS 类型错误:无法读取未定义的属性'className'



我正在尝试构建一个菜单,突出显示用户所在的当前选项卡/页面,添加一个颜色类,并使用JavaScript更新活动链接。这是我的模板:

<div class="w3-bar w3-black">
<button
class="w3-bar-item w3-button tablink w3-red"
onclick="openCity(event,'London')"
>
London
</button>
<button
class="w3-bar-item w3-button tablink"
onclick="openCity(event,'Paris')"
>
Paris
</button>
<button
class="w3-bar-item w3-button tablink"
onclick="openCity(event,'Tokyo')"
>
Tokyo
</button>
</div>
<div id="London" class="w3-container w3-border city">
<h2>London</h2>
<p>London is the capital city of England.</p>
</div>
<div id="Paris" class="w3-container w3-border city" style="display:none">
<h2>Paris</h2>
<p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="w3-container w3-border city" style="display:none">
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</div>

我在"方法"中有这样的javascript代码:

methods: {
openCity: function(evt, cityName) {
var i, x, tablinks;
x = document.getElementsByClassName("city");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < x.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" w3-red", "");
}
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " w3-red";
}
}

但我在控制台中遇到了这个错误:"TypeError:无法读取未定义的属性"className",并且按钮没有突出显示它。"。希望你能帮助我,谢谢!

您传递的是event而不是$event,我认为这就是为什么没有定义它。此外,您还有很多不必要的代码。我把它清理干净了,现在试试:

HTML

<div class="w3-bar w3-black">
<button
v-for="city in cities"
class="w3-bar-item w3-button tablink"
@click="openCity($event, city)"
:class="{ 
'w3-red': city.name === selectedCity,
'w3-black': city.name !== selectedCity 
}"
>
{{city.name}}
</button>
</div>
<div 
v-for="city in cities" 
:id="city.name" 
class="w3-container w3-border city"
:class="{ 
'visible': city.name === selectedCity,
'hidden': city.name !== selectedCity 
}"
>
<h2>{{city.name}}</h2>
<p>{{city.description}}</p>
</div>

脚本

data () {
return {
selectedCity: 'London',
cities: [
{ 
name: 'London', 
description: 'London is the capital city of England'
},
{ 
name: 'Paris', 
description: 'Paris is the capital of France',
},
{ 
name: 'Tokyo', 
description: 'Tokyo is the capital of Japan',
}
] 
}
},
methods: {
openCity (event, city) {
this.selectedCity = city.name
}
}

样式

.hidden {
display: none
}
.visible {
display: block
}

方法2

如果你不想使用CSS类来隐藏内容,你可以只使用v-show,并且只显示选定的城市city.name === selectedCity:

<div 
v-for="city in cities" 
v-show="city.name === selectedCity"
:id="city.name" 
class="w3-container w3-border city"
>
<h2>{{city.name}}</h2>
<p>{{city.description}}</p>
</div>

最新更新