【问题标题】:Nuxt.js run code on page loadNuxt.js 在页面加载时运行代码
【发布时间】:2018-08-12 16:00:12
【问题描述】:

当page 加载 Nuxt.js 时如何运行代码?

如果浏览器支持使用!!window.ontouchstart 的触摸事件,我想添加一个类。

我试过了,但 window 未定义:

```
<section v-bind:class="{ touch: !!window.ontouchstart }">
   ...
</section>
```

【问题讨论】:

  • 查看了 10,000 次。一个赞成票。

标签: vue.js vuejs2 nuxt.js


【解决方案1】:

你需要先添加一个eventlistener来监听touchstart。

created: function(){
    document.addEventListener('touchstart',this.touchStart);
 }, 
destroyed: function() { 
    document.removeEventListener('touchstart', this.touchStart); 
 }

现在你可以使用 touch touchStart 方法了 在 Vue 方法中。

methods:{
  touchStart(e){
    this.touched=true;
  }

}

在html中

<section v-bind:class="{ touch: touched}"> ... </section>

另外ontouchstart是一个尚未标准化的窗口事件, 所以用window替换document。

【讨论】:

  • Hmmm... 当created 函数在服务器端渲染期间运行时,这会创建一个ReferenceError "document is not defined"。 window 也一样。 Nuxt 中document 的策略是什么?
  • @MichaelCole 你需要使用mounted 钩子,created 也在服务器上执行(没有窗口/文档)
  • @FabianvonEllerts 是正确的。我还要补充一点,当“created”钩子运行时,Vue 不能保证 DOM 已经完全渲染,因此所有 html 节点可能都没有准备好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-23
  • 2015-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-20
相关资源
最近更新 更多