我正在尝试在Vue条件内使用window对象:
<li v-if="window.SpeechRecognition || window.webkitSpeechRecognition">
<a href="#">Voice</a>
</li>
但是我遇到以下错误:
[Vue warn]: Property or method "window" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
如何解决此错误,并且仅在用户的浏览器支持功能SpeechRecognition
时才显示HTML元素?
答案 0 :(得分:5)
您只能在模板中引用范围为相关Vue实例的变量。警告是说您的Vue实例没有名为window
的属性或方法(无论如何,这不是您要引用的属性或方法)。
只需将Vue实例(speechRecognition
或其他内容)上的data属性设置为v-if
语句中的值,然后引用该值,而不是尝试直接从中访问window
对象在您的模板中(无法完成):
data() {
return {
speechRecognition: window.SpeechRecognition || window.webkitSpeechRecognition,
}
}
<li v-if="speechRecognition">
<a href="#">Voice</a>
</li>