iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 7
1
Modern Web

「VR 」前端後端交響曲 - 30天開發 Vue.js feat. Ruby on Rails即時互動網站系列 第 7

[VR 前後端交響曲Day7] 在Rails專案內加上Vue元件

經過了三天的Vue簡單起手式,接著我們要回到Rails專案內實作了。(捲起袖子)
今天來了解一下元件的概念!

元件component:堆樂高積木的概念

在開發的時候,管理團隊專案內JavaScript檔案一直是一件充滿挑戰的任務。自從框架帶來了元件components的概念後,重複使用的功能可以獨立出來成為一個一個可以重複使用的「積木」,讓跟特定區塊有關的htmlcssJavaScript都集中在同個component。程式更好維護、更易於重複使用,也更不容易出錯了~

示意圖:元件就像樂高積木一樣

(pic credit:)

我們可以想像Vue的每個元件都是一個UI,各自具有template標籤(html)、state狀態(js)及style樣式(css)

(pic credit:)

每個Vue元件的架構,固定寫法長這樣(可以把這段程式碼在你喜愛的編輯器裡存成snippet~開發更快速唷):

<template>
// 這裡放html
</template>

<script>
// import Another from "/components/another.vue";

export default {
  name: '',
  data: function () {
    return {
    };
  },
  // components: { Another },
};
</script>

<style scoped>
// 這裡放css
</style>

特別注意的是,在component裡的data屬性,需要是一個有return值的function,每次回傳該元件專屬的狀態及資料。

註冊元件

當我們想要使用某一塊積木(例如上述程式碼註解的部分Another這塊積木時候),必須先import引入積木的位置、然後再來到components: { Another }這個位置註冊,根據慣例,元件名字的開頭大寫。

Rails專案示範:掛component

學習新主題的時候,我習慣先來個最小可行解試試手感:

如下面Gif圖所示,當我在Rails專案某一個頁面的Root元件裡有一塊foot區域,要怎麼把這一塊改成component呢?

首先:在 html規劃好架構
pages#home.html.erb

<div id="main-area">
  <div class="main-title">Vue.js x Rails{{ title }}</div>
  <div class="main-body">本日主題:Rails專案內加上Vue元件</div>
  <Foot></Foot>
</div>

我的Root元件:main-page.js:

import TurbolinksAdapter from 'vue-turbolinks'
import Vue from 'vue/dist/vue.esm'
import Foot from '../components/foot'


Vue.use(TurbolinksAdapter)

document.addEventListener('turbolinks:load', () => {
  let el = document.querySelector("#main-area");

  if (el){
    new Vue({
      el,
      data: () => {
        return {
          title: " 第12屆鐵人賽專案"
        }
      },
      components: { Foot }
    })    
  }
})

/frontend/components/foot.vue

接著,就是~推積木時間~要產生一塊元件了~
foot這塊元件的template用第四天介紹的鬍子語法把我的版權宣告內容傳進來。
然後在style scoped稍微調了一下css,這個scoped代表元件區域內的css不會影響到其他地方的css喔!便利ですね〜

<template>
  <div class="footer">
    <div class="footer-content">{{ trademark }}</div>
  </div>
</template>

<script>
export default {
  name: '',
  data: function () {
    return {
      trademark: "by Ting Ting. All rights reserved."
    };
  }
};
</script>

<style scoped>
  .footer{
    background-color: rgb(252, 252, 218);
    width: 100%;
    height: 20vh;
    position:absolute;
    bottom:0px;
    left:0px;
    font-size: 10px;
  }
  .footer-content{
    padding-top: 60px;
    text-align: center;
  }
</style>

成功地在Rails首頁的掛好第一個元件囉!

但現在有一個大哉問:

如果以後我們有了多個各自獨立的元件之後,不同的Vue元件該如何傳遞與分享資料呢?
明天要來深入研究元件資料的props屬性:)

Ref:


上一篇
[VR 前後端交響曲Day6] Vue元件中的computed屬性
下一篇
[VR 前後端交響曲Day8] 由外到內:Vue元件裡的props屬性(1)
系列文
「VR 」前端後端交響曲 - 30天開發 Vue.js feat. Ruby on Rails即時互動網站30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言