Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue - How to use window object inside v-if or components

I'm trying to use the window object inside a Vue condition:

<li v-if="window.SpeechRecognition || window.webkitSpeechRecognition">
    <a href="#">Voice</a>
</li>

But I'm getting the following error:

[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.

How can I work around this error and only display the HTML element if the user's browser has support for the functions SpeechRecognition?

like image 444
Caio Kawasaki Avatar asked Nov 14 '18 14:11

Caio Kawasaki


1 Answers

You can only reference variables in the template that are scoped to the related Vue instance. The warning is saying that your Vue instance doesn't have a property or method named window (which isn't what you are trying to refer to anyway).

Just set a data property on the Vue instance (speechRecognition or whatever) to the value in your v-if statement and then reference that instead of trying to directly access the window object from inside your template (which can't be done):

data() {
  return {
    speechRecognition: window.SpeechRecognition || window.webkitSpeechRecognition,
  }
}

<li v-if="speechRecognition">
  <a href="#">Voice</a>
</li>
like image 94
thanksd Avatar answered Sep 20 '22 10:09

thanksd