iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 29
1
自我挑戰組

愛寫什麼就寫什麼,開心最重要系列 第 29

Day29-Alpine.js vs Vue.js淺談(5)

今天要比較的是「屬性綁定」,
Alpine.js使用的是x-bind:屬性=""
Vue.js使用的是v-bind:屬性=""
兩者皆可簡化成 :屬性=""
接著讓我們來看範例吧。

共同css

.hidden {
  display: none;
}

Alpine.js

html

  <div x-data="{
    post: {
      title: 'My first post',
      featuredImage: 'https://dummyimage.com/600x400',
      isPublished: false
    },
    isOnMobile: true,
  }">
  
    <h3 x-text="post.title"></h3>
    
    <div>img1</div>
    <img 
    x-bind:src="post.featuredImage" 
    x-bind:alt="post.title"
    >
    <hr>
    
    <div>img2</div>
    <img x-bind:class="{ hidden: isOnMobile }">
    <hr>
    
    <button x-bind:disabled="post.isPublished">Publish</button>
  </div>

這邊主要拆成3個部分,
第一,img1底下帶入
x-bind:src="post.featuredImage"
x-bind:alt="post.title"
就是將x-data內所對應的質帶入就會顯示對應的屬性了

第二,img2底下帶入
x-bind:class="{ hidden: isOnMobile }"
意思是當isOnMobile條件為true時,該標籤會有hidden的class
而上面.hidden的css已經寫好了,
就會直接被帶入,
所以這張圖就不會顯示出來了。

第三,在button中帶入
x-bind:disabled="post.isPublished"
意思是當post.isPublished條件為true時,該標籤會有disabled的屬性

Vue.js

html

<template>
  <div>
    <h3>{{ post.title }}</h3>

    <div>img1</div>
    <img
      v-bind:src="post.featuredImage"
      v-bind:alt="post.title"
    >
    <hr>
    
    <div>img2</div>
    <img v-bind:class="{ hidden: isOnMobile }">
    <hr>
    
    <button v-bind:disabled="post.isPublished">Publish</button>
  </div>
</template>

js

  export default {
    name: 'App',
    data() {
      return {
        post: {
          title: "My first post",
          featuredImage: "https://dummyimage.com/600x400",
          isPublished: false
        },
        isOnMobile: true
      }
    }
  }

大家其實可以比較一下,
條件都一樣只是寫的方式不一樣而已,
用法幾乎是一模一樣,
有興趣的可以玩看看~


上一篇
Day28-Alpine.js vs Vue.js淺談(5)
下一篇
Day30-鐵人三十天回顧Alpine.js總整理
系列文
愛寫什麼就寫什麼,開心最重要30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言