最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Nov 14, 2018 at 14:43 Caio Kawasaki asked Nov 14, 2018 at 14:20 Caio KawasakiCaio Kawasaki 2,9507 gold badges37 silver badges73 bronze badges 2
  • Does this answer in the Vue forums help? – vahdet Commented Nov 14, 2018 at 14:24
  • What vahdet linked. To explain... while in the DOM the scope is "this" (the component) so it is trying to do this.window. instead of window. – Marc Commented Nov 14, 2018 at 14:27
Add a comment  | 

2 Answers 2

Reset to default 15

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>

Define this in your data and use the window in the template, hope it will work.

data() {
    return {
      window: window
    }
  },
发布评论

评论列表(0)

  1. 暂无评论