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.pswp.cn/news/394575.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394575.shtml
英文地址,請注明出處:http://en.pswp.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…