javascript - Rails 应用程序中的 Vue 生命周期 Hook

标签 javascript ruby-on-rails vue.js

我的其他 Rails 应用程序中有一些 Vue 组件,我注意到 mounted() 生命周期钩子(Hook)在不同的时间触发,这取决于我是被路由到带有组件的页面还是已经在页面上,我刷新浏览器。

这很重要,因为我在组件初始化时需要在 DOM 中有一些 $refs 变量。

mounted: function() {
    let user = {
      user_type: parseInt(that.$refs.user.dataset.user_type),
      location_id: parseInt(that.$refs.user.dataset.location)
    }
}

此函数在页面刷新时成功执行,但当我转到那里时抛出以下错误:

Uncaught TypeError: Cannot read property 'dataset' of undefined

当它明确在 DOM 中时:

<div ref="user" data-user_type="<%= current_user.user_type %>" data-location="<%= current_user.employee.location_id %>"></div>

我知道这与时间有关,但我不确定如何解决这个问题。

最佳答案

我能够使用 jQuery 提取信息:

let user = {
  user_type: $('[data-user_type]').data('user_type'),
  location_id: $('[data-user_type]').data('location')
}

关于javascript - Rails 应用程序中的 Vue 生命周期 Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48791540/

相关文章:

javascript - 如何引用对象本身?

javascript - 每x秒从服务器请求数据的最佳方式

javascript - Vue - 无法获取父组件数据

vue.js - 迭代具有不同起点和终点的数组

laravel - 未设置/存储 Httponly cookie (Laravel/Vue)

javascript - 查找沃尔玛的搜索 URL

javascript - 如何在CoffeeScript中循环输出多个对象的属性?

ruby-on-rails - 闲置/闲置后自动注销

ruby-on-rails - ruby /Rails : suppress superclass functions - integration of Stripe and Devise

ruby-on-rails - 带有 JRuby 的 Google App Engine - 有人可以提供 appengine-jruby、warble 等的概述吗?