我的其他 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/