rails 共享变量_如何将Rails实例变量传递给Vue组件

rails 共享变量

by Gareth Fuller

由Gareth Fuller

如何将Rails实例变量传递给Vue组件 (How to pass Rails instance variables into Vue components)

I’m currently working with a legacy Rails application. We are slowly transitioning the front-end from Rails views to a Vue application.

我目前正在使用旧版Rails应用程序。 我们正在将前端从Rails视图逐步过渡到Vue应用程序。

As part of this transition, we have some elements that we want to turn into global Vue components. We want to be able to use these components within our existing Rails views and within a Vue application without having to customize each component to handle both situations.

作为此过渡的一部分,我们希望将某些元素转变为全局Vue组件。 我们希望能够在我们现有的Rails视图和Vue应用程序中使用这些组件,而不必自定义每个组件来处理这两种情况。

Before I share my solution to this problem, here is an example single file Vue component that we want to be able to use in both scenarios (Rails view and Vue Application):

在分享我对这个问题的解决方案之前,这是一个示例单文件Vue组件,我们希望在两个场景(Rails视图和Vue Application)中都可以使用:

// Payments.vue
<template lang="html">  <div id="payments>    <div class="payment" v-for="payment in payments>      {{ payment.amount }}    </div>  </div></template>
<script>export default {  name: 'payments'
props: {    payments: { type: Array }  }}</script>
<style lang="scss" scoped></style>

From within a Vue app, this is a straightforward component to use, right? For example:

在Vue应用程序中,这是一个易于使用的组件,对吗? 例如:

// app/javascript/App.vue
<template lang="html">  <div id="app>    <payments :payments="payments" />  </div></template>
<script>import Payments from './Payments.vue'
export default {  name: 'app',
components: { Payments },
data () {    return {      payments: [        { amount: 123.00 },        { amount: 124.00 }      ]    }  }</script>
<style lang="scss" scoped></style>

But what about using it in a Rails view?

但是在Rails视图中使用它呢?

(Solution)

So a solution for using the Payments.vue component in Rails looks like this:

因此,在Rails中使用Payments.vue组件的解决方案如下所示:

// app/views/payments/index.haml
.global-comp  = content_tag 'comp-wrapper', nil, data: { component: 'payments', props: { payments: @payments } }.to_json

Let’s break this element down.

让我们分解一下这个元素。

.global-comp is a div (with class “global-comp”) for mounting a super simple Vue instance. This Vue instance gives us a wrapper component to use called CompWrapper.vue (we’ll get to what CompWrapper is for in a minute).

.global-comp是用于挂载超简单Vue实例的div(类为“ global-comp”)。 这个Vue实例为我们提供了一个名为CompWrapper.vue的包装器组件(稍后我们将介绍CompWrapper的用途)。

Here is the Vue instance mounted to .global-comp:

这是安装到.global-comp的Vue实例:

// app/javascript/packs/global_comp.js
import Vue from 'vue/dist/vue.esm'import CompWrapper from './CompWrapper'
document.addEventListener('DOMContentLoaded', () => {  const app = new Vue({    components: { CompWrapper }  }).$mount('.global-comp')})

All this does is make the component (CompWrapper.vue) available to us within a div with the class global-comp.

所有这些操作就是使组件( CompWrapper.vue )在类中具有global-comp类的div可供我们使用。

If you are using Webpacker with Rails, you will need to include this pack within your layout somewhere before the closing body tag. For example:

如果您将Webpacker与Rails一起使用,则需要在封闭body标记之前的某个位置将此包包含在布局中。 例如:

// app/views/layouts/application.haml
...
= javascript_pack_tag "global_comp"

CompWrapper.vue (CompWrapper.vue)

This is the fun part. CompWrapper.vue allows us to pass:

这是有趣的部分。 CompWrapper.vue允许我们传递:

  1. The name of the component we want to use, for example, “payments”

    我们要使用的组件名称,例如“付款”
  2. The props we want to pass to it

    我们想要传递给它的道具

The whole purpose of this wrapper component is to allow us to pass Rails instance variables like @payments into our components as props without having to handle this from within each component like Payments.vue.

包装器组件的全部目的是使我们可以将@payments类的Rails实例变量作为@payments到我们的组件中,而不必从Payments.vue之类的每个组件中进行处理

So here is CompWrapper.vue:

所以这是CompWrapper.vue

// app/javascript/CompWrapper.vue
<template lang="html">  <component :is="data.component" v-bind="data.props"></component></template>
<script>import * as components from './components'
export default {  name: 'comp-wrapper',
components,
data () {    return {      data: {}    }  },
created() {    this.data = JSON.parse(this.$attrs.data)  }}</script>
<style lang="scss" scoped></style>

The first thing the CompWrapper component is doing is taking the data attributes you set on the element in the Rails view, parsing the JSON, and setting an internal Vue data attribute with the parsed data:

CompWrapper组件要做的第一件事是获取您在Rails视图中的元素上设置的数据属性,解析JSON,并使用解析的数据设置内部Vue数据属性:

created() {  this.data = JSON.parse(this.$attrs.data)}

with this.data set we can then use it to select the component we want to use and pass it the props we provided in our Rails view using a Vue dynamic component:

有了this.data集,我们可以使用它来选择我们要使用的组件,并使用Vue动态组件将我们在Rails视图中提供的道具传递给它:

<component :is="data.component" v-bind="data.props"></component>

And that’s it!

就是这样!

We can now use Vue components as they’re meant to be used, but from within our rails views. ?

现在,我们可以按原样使用Vue组件,但可以在rails视图中使用。 ?

翻译自: https://www.freecodecamp.org/news/how-to-pass-rails-instance-variables-into-vue-components-7fed2a14babf/

rails 共享变量

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/394575.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Leetcode: Counting Bits

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1s in their binary representation and return them as an array.Example: For num 5 you should return [0,1,1,2,1,2].Follow up:It is very easy to c…

第一个python爬虫_Python爬虫01——第一个小爬虫

Python小爬虫——贴吧图片的爬取 在对Python有了一定的基础学习后&#xff0c;进行贴吧图片抓取小程序的编写。 目标&#xff1a; 首先肯定要实现图片抓取这个基本功能 然后实现对用户所给的链接进行抓取 最后要有一定的交互&#xff0c;程序不能太傻吧 一、页面获取 要让pytho…

Mac下,如何把项目托管到Github上(Github Desktop的使用)

在上一篇中&#xff0c;详细讲解了使用X-code和终端配合上传代码的方法&#xff0c;这种方法比较传统&#xff0c;中间会有坑&#xff0c;英文看起来也费劲&#xff0c;不过Github官方提供了一个Mac版的客户端&#xff0c;如下图&#xff1a; 附上下载链接&#xff1a;传送门 下…

计算机网络英文面试题,计算机网络面试题整理

GET和POST的区别&#xff1f;GET和POST方法没有实质上区别&#xff0c;只是报文格式不同。GET和POST是HTTP协议中的两种请求方法。而 HTTP 协议是基于 TCP/IP 的应用层协议&#xff0c;无论 GET 还是 POST&#xff0c;用的都是同一个传输层协议&#xff0c;所以在传输上&#x…

利用递归求某数的阶乘——C/C++

#include<stdio.h>int getFactorial(int n) {if(n0)return 1;else return n*getFactorial(n-1); }int main() {int n,res;scanf("%d",&n);res getFactorial(n);printf("%d",res);return 0; } 转载于:https://www.cnblogs.com/daemon94011/p/106…

intern_充分利用Outreachy Intern申请流程

internby Joannah Nanjekye乔安娜南耶基(Joannah Nanjekye) 充分利用Outreachy Intern申请流程 (Get the most out of your Outreachy Intern application process) Outreachy gives three-month paid internships for persons that are underrepresented in tech. Interns ar…

Put-Me-Down项目Postmortem2

一.设想和目标二.计划三.资源四.变更管理五.设计/实现六.测试/发布总结一.设想和目标 1. 我们的软件要解决什么问题&#xff1f;是否定义得很清楚&#xff1f;是否对典型用户和典型场景有清晰的描述&#xff1f; 我们的软件要帮助低头族控制使用手机时间。功能很明确&#xff0…

大数据实验报告总结体会_建设大数据中台架构思考与总结

简介本文介绍完善的大数据中台架构了解这些架构里每个部分的位置&#xff0c;功能和含义及背后原理及应用场景。帮助技术与产品经理对大数据技术体系有个全面的了解。数据中台定义&#xff1a;集成离线数仓与实时数仓&#xff0c;并以多数据源统一整合采集到kafka,再通过kafka进…

半数集问题

给定一个自然数n&#xff0c;由n开始可以依次产生半数集set(n)中的数如下&#xff1a; (1) n ∈set(n)&#xff1b; (2) 在n的左边加上一个自然数&#xff0c;但该自然数不能超过最近添加的数的一半&#xff1b; (3) 按此规则进行处理&#xff0c;直到不能再添加自然数为止。…

微型计算机控制理论基础答案,微型计算机控制技术试卷c

微型计算机控制技术试卷a潘新民 微型计算机控制技术实用教程微型计算机控制技术试卷C一、选择题(本题共10小题&#xff0c;每小题 1.5分&#xff0c;共15分)1. DAC0832的VREF接-5V&#xff0c;IOUT1接运算放大器异名端&#xff0c;输入为1000000B &#xff0c;输出为( )。A. 5V…

aws lambda_四处奔走:初学者遇到AWS Lambda

aws lambdaby Janaka Bandara通过Janaka Bandara 四处奔走&#xff1a;初学者遇到AWS Lambda (Running around the block: a beginner meets AWS Lambda) Computing! It sure has a very long, vivid (and sometimes awkward) history. Some key milestones include:计算&…

python打开快捷方式_Python创建启动目录的快捷方式,python,到

# -*- coding:utf-8 -*-# author&#xff1a;lizonezhiimport osimport sysimport pythoncomimport win32com.client as clientdef createShortCut(filename): # 目前创建的无起始位置"""filename should be abspath, or there will be some strange errors&quo…

二叉树的基本操作及应用(三)

#include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <string.h> typedef char DataType; int depth0; int h11; int nlayer1; char ch2; typedef struct node {DataType data;//节点数据元素struct node *lchild;//指向左孩子struc…

maven的profile详解

详细内容请见&#xff1a;https://www.cnblogs.com/wxgblogs/p/6696229.html Profile能让你为一个特殊的环境自定义一个特殊的构建&#xff1b;profile使得不同环境间构建的可移植性成为可能。Maven中的profile是一组可选的配置&#xff0c;可以用来设置或者覆盖配置默认值。有…

夏至未至计算机版音乐,夏至未至有哪些插曲背景音乐 夏至未至所有bgm歌曲汇总...

夏至未至有哪些插曲背景音乐 夏至未至所有bgm歌曲汇总夏至未至第一集插曲是什么?夏至未至插曲曝光。夏至未至是由陈学冬、郑爽、白敬亭等联袂主演的青春偶像剧,昨晚已经开播了&#xff0c;那么第一集的插曲是什么呢?和小编一起去看看吧!夏至未至第一集插曲《那些花儿》那片笑…

了解如何在20分钟内创建您的第一个Angular应用

Angular is a JavaScript framework, created my Misko Hevery and maintained by Google. It’s an MVC (Model View Vontroller). You can visit the official page to learn more about it.Angular是一个JavaScript框架&#xff0c;创建了我的Misko Hevery&#xff0c;并由G…

js闭包使用

闭包就是在一个函数内定义一个内部函数 并返回内部函数 function f1(){var a1; addfunction(){aa1;} function f1Sub(){ console.log(a); } return f1Sub; } var ff1();f();add();f();var f2f1();add();f(); 输出为 1 2 2 可以看到输出结果 定义f2后执行add 这时 f2的add函数已…

BIO,NIO,AIO总结(二)

这里重点介绍NIO 待定 http://www.apigo.cn/2018/11/09/javacore5/ https://juejin.im/entry/598da7d16fb9a03c42431ed3 https://mp.weixin.qq.com/s/c9tkrokcDQR375kiwCeV9w?转载于:https://www.cnblogs.com/smallJunJun/p/10607078.html

思科配置计算机ip地址子网掩码,计算机系统与网络技术IP地址 子网掩码 主机号等计算复习...

IP地址 子网掩码 主机号等计算复习IP地址、子网掩码、网络号、主机号、网络地址、主机地址复习 IP地址&#xff1a;4段十进制&#xff0c;共32位二进制&#xff0c;如&#xff1a;192.168.1.1 二进制就是&#xff1a;11000000&#xff5c;10101000&#xff5c;00000001&#xf…

nmap常用参数详解

nmap常用参数详解 作者&#xff1a;尹正杰 版权声明&#xff1a;原创作品&#xff0c;谢绝转载&#xff01;否则将追究法律责任。 借用英雄联盟的一个英雄赵信的一句话&#xff1a;“即使敌众我寡,末将亦能万军丛中取敌将首级!”。三国关羽&#xff0c;万军丛中斩了颜良&#x…