简体   繁体   English

Vue生命周期钩在rails应用程序中

[英]Vue lifecycle hooks in rails app

I have a few Vue components in my otherwise Rails app and I noticed that the mounted() lifecycle hook fires at different times, depending on whether I am routed to the page with the component or am already on the page and I refresh the browser. 我在其他Rails应用程序中有一些Vue组件,我注意到mounted()生命周期钩子在不同时间触发,具体取决于我是否使用该组件路由到页面,或者我已经在页面上并刷新浏览器。

It's important because I have some $refs variables in the DOM that I need on component initialization. 这很重要,因为我在DOM中有一些$refs变量,我需要在组件初始化时使用。

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

This function executes successfully on page refresh, but throws the following error when I am routed there: 此功能在页面刷新时成功执行,但在我路由时会抛出以下错误:

Uncaught TypeError: Cannot read property 'dataset' of undefined 未捕获的TypeError:无法读取未定义的属性“dataset”

when it is clearly in the DOM: 当它显然在DOM中时:

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

I know it has to do with timing, but am unsure how to remedy the issue. 我知道这与时间有关,但我不确定如何解决这个问题。

I was able to pull down the information using jQuery: 我能够使用jQuery下拉信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM