【问题标题】:How to access Rails instance variable from Vue.js component?如何从 Vue.js 组件访问 Rails 实例变量?
【发布时间】:2021-10-31 13:08:57
【问题描述】:

我正在尝试从 Vue 组件访问 rails 实例变量。我不确定这是否可能。我的控制器代码如下所示

class ResultsController < ApplicationController
  def index
     @role = @current_user.role # I need to access this instance variable in Vue component.
  end
end

而我的 Vue 组件看起来像这样

<template>
  <v-container class="my-1 py-0">
    <v-card>
      <a v-bind:href="`/score_cards/new?tournament_match_id=${match.DT_RowId}`">Upload Score Card</a> # I want to display this link only when @role == 'admin'
    </v-card>
  </v-container>
</template>

所以我只想在@role == 'admin' 时显示Upload Score Card 链接。那么我怎样才能做到这一点是 Vue.js 呢?如何在 Vue 中访问 @role 实例变量?

【问题讨论】:

    标签: ruby-on-rails vue.js


    【解决方案1】:

    您可以将 Rails 变量传递给 Javascript,但您需要先将它们嵌入到 HTML 页面中,然后您的 JS 代码从 HTML 中读取它们。

    像这样将变量插入 HTML。

    <%= content_tag :div, class: "variables", data: { 
      first_variable: @variable_1,
      second_variable: @variable_2 
    } do %>
    <% end %>
    

    这将在生成的网页中像这样输出div

    <div class="variables" data-first-variable="[VALUE]" data-second-variable="[VALUE]">
    

    然后你像这样将它们读入你的 JS。

    $('.variables').data('firstVariable')
    

    (如您所见,这是 JQuery 表示法,但我相信您可以在 Vue 中做类似的事情。)

    【讨论】:

      猜你喜欢
      • 2016-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-13
      • 2010-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多