Vue 3 vs Alpine Comparison

Declare state

Vue 3

<script setup>
import { ref } from "vue";
const name = ref("John");
</script>

<template>
  <h1>Hello {{ name }}</h1>
</template>

Alpine

<h1 x-data="{ name: 'John' }" x-text="name"></h1>

Update state

Vue 3

<script setup>
import { ref } from "vue";
const name = ref("John");
name.value = "Jane";
</script>

<template>
  <h1>Hello {{ name }}</h1>
</template>

Alpine

<h1 x-data="{ name: 'John' }" x-init="name = 'Jane'" x-text="name"></h1>

Computed state

Vue 3

<script setup>
import { ref, computed } from "vue";
const count = ref(10);
const doubleCount = computed(() => count.value * 2);
</script>

<template>
  <div>{{ doubleCount }}</div>
</template>

Alpine

<h1
  x-data="{
  count : 10,
  get doubleCount() { return this.count * 2 }
}"
  x-text="doubleCount"
></h1>

Templating

Minimal template

Vue 3

<template>
  <h1>Hello world</h1>
</template>

Alpine

<h1>Hello world</h1>

Styling

Vue 3

<template>
  <h1 class="title">I am red</h1>
  <button style="font-size: 10rem">I am a button</button>
</template>

<style scoped>
.title {
  color: red;
}
</style>

Alpine

<h1 class="title">I am red</h1>
<button style="font-size: 10rem">I am a button</button>

<style>
  .title {
    color: red;
  }
</style>

Loop

Vue 3

<script setup>
const colors = ["red", "green", "blue"];
</script>

<template>
  <ul>
    <li v-for="color in colors" :key="color">
      {{ color }}
    </li>
  </ul>
</template>

Alpine

<ul x-data="{ colors: ['red', 'green', 'blue'] }">
  <template x-for="color in colors">
    <li x-text="color"></li>
  </template>
</ul>

Event click

Vue 3

<script setup>
import { ref } from "vue";
const count = ref(0);

function incrementCount() {
  count.value++;
}
</script>

<template>
  <p>Counter: {{ count }}</p>
  <button @click="incrementCount">+1</button>
</template>

Alpine

<div x-data="{ count: 0 }">
  <p>Counter: <span x-text="count"></span></p>
  <button x-on:click="count++">+1</button>
</div>

DOM ref

Vue 3

<script setup>
import { useTemplateRef, onMounted } from "vue";

const inputElement = useTemplateRef("inputElement");

onMounted(() => {
  inputElement.value.focus();
});
</script>

<template>
  <input ref="inputElement" />
</template>

Alpine

<input x-init="$el.focus();" />

Conditional

Vue 3

<script setup>
import { ref, computed } from "vue";
const TRAFFIC_LIGHTS = ["red", "orange", "green"];
const lightIndex = ref(0);

const light = computed(() => TRAFFIC_LIGHTS[lightIndex.value]);

function nextLight() {
  lightIndex.value = (lightIndex.value + 1) % TRAFFIC_LIGHTS.length;
}
</script>

<template>
  <button @click="nextLight">Next light</button>
  <p>Light is: {{ light }}</p>
  <p>
    You must
    <span v-if="light === 'red'">STOP</span>
    <span v-else-if="light === 'orange'">SLOW DOWN</span>
    <span v-else-if="light === 'green'">GO</span>
  </p>
</template>

Alpine

<div
  x-data="{
  TRAFFIC_LIGHTS: ['red', 'orange', 'green'],
  lightIndex: 0,
  get light() { return this.TRAFFIC_LIGHTS[this.lightIndex] },
  nextLight() {
    this.lightIndex = (this.lightIndex + 1) % this.TRAFFIC_LIGHTS.length;
  }
}"
>
  <button x-on:click="nextLight">Next light</button>
  <p>Light is: <span x-text="light"></span></p>
  <p>
    You must
    <span x-show="light === 'red'">STOP</span>
    <span x-show="light === 'orange'">SLOW DOWN</span>
    <span x-show="light === 'green'">GO</span>
  </p>
</div>

Lifecycle

On mount

Vue 3

<script setup>
import { ref, onMounted } from "vue";
const pageTitle = ref("");
onMounted(() => {
  pageTitle.value = document.title;
});
</script>

<template>
  <p>Page title: {{ pageTitle }}</p>
</template>

Alpine

<p
  x-data="{ pageTitle: '' }"
  x-init="$nextTick(() => { pageTitle = document.title })"
>
  Page title: <span x-text="pageTitle"></span>
</p>

On unmount

Vue 3

<script setup>
import { ref, onUnmounted } from "vue";

const time = ref(new Date().toLocaleTimeString());

const timer = setInterval(() => {
  time.value = new Date().toLocaleTimeString();
}, 1000);

onUnmounted(() => {
  clearInterval(timer);
});
</script>

<template>
  <p>Current time: {{ time }}</p>
</template>

Alpine

<p
  x-data="{
  time: new Date().toLocaleTimeString(),
  timer: null,
  init() { this.timer = setInterval(() => (this.time = new Date().toLocaleTimeString()), 1000) },
  destroy() { clearInterval(this.timer) }
}"
>
  Current time: <span x-text="time"></span>
</p>

Component composition

Props

Vue 3

<script setup>
import UserProfile from "./UserProfile.vue";
</script>

<template>
  <UserProfile
    name="John"
    :age="20"
    :favourite-colors="['green', 'blue', 'red']"
    is-available
  />
</template>

Alpine

<!--Alpine JS suggests using a server-side templating engine or another frontend framework in conjunction with Alpine to do this-->

<div
  x-data="{
  name: 'John',
  age: 20,
  favouriteColors: ['green', 'blue', 'red'],
  isAvailable: true
}"
>
  <p>My name is <span x-text="John"></span></p>
  <p>My age is <span x-text="age"></span></p>
  <p>
    My favourite colors are <span x-text="favouriteColors.join(', ')"></span>
  </p>
  <p>I am <span x-text="isAvailable ? 'available' : 'not available'"></span></p>
</div>

Emit to parent

Vue 3

<script setup>
import { ref } from "vue";
import AnswerButton from "./AnswerButton.vue";

let isHappy = ref(true);

function onAnswerNo() {
  isHappy.value = false;
}

function onAnswerYes() {
  isHappy.value = true;
}
</script>

<template>
  <p>Are you happy?</p>
  <AnswerButton @yes="onAnswerYes" @no="onAnswerNo" />
  <p style="font-size: 50px">
    {{ isHappy ? "😀" : "😥" }}
  </p>
</template>

Alpine

<div
  x-data="{ isHappy: true }"
  x-on:yes="isHappy = true"
  x-on:no="isHappy = false"
>
  <p>Are you happy?</p>
  <div>
    <button x-on:click="$dispatch('yes')">YES</button>
    <button x-on:click="$dispatch('no')">NO</button>
  </div>
  <p style="font-size: 50px" x-text="isHappy ? '😀' : '😥'"></p>
</div>

Slot

Vue 3

<script setup>
import FunnyButton from "./FunnyButton.vue";
</script>

<template>
  <FunnyButton> Click me! </FunnyButton>
</template>

Alpine

<!--Alpine JS suggests using a server-side templating engine or another frontend framework in conjunction with Alpine to do this-->

<button
  x-data
  x-text="'Click me!'"
  style="
    background: rgba(0, 0, 0, 0.4);
    color: #fff;
    padding: 10px 20px;
    font-size: 30px;
    border: 2px solid #fff;
    margin: 8px;
    transform: scale(0.9);
    box-shadow: 4px 4px rgba(0, 0, 0, 0.4);
    transition: transform 0.2s cubic-bezier(0.34, 1.65, 0.88, 0.925) 0s;
    outline: 0;
  "
>
  <span>No content found</span>
</button>

Slot fallback

Vue 3

<script setup>
import FunnyButton from "./FunnyButton.vue";
</script>

<template>
  <FunnyButton />
  <FunnyButton> I got content! </FunnyButton>
</template>

Alpine

<!--Alpine JS suggests using a server-side templating engine or another frontend framework in conjunction with Alpine to do this-->

<button
  x-data
  style="
    background: rgba(0, 0, 0, 0.4);
    color: #fff;
    padding: 10px 20px;
    font-size: 30px;
    border: 2px solid #fff;
    margin: 8px;
    transform: scale(0.9);
    box-shadow: 4px 4px rgba(0, 0, 0, 0.4);
    transition: transform 0.2s cubic-bezier(0.34, 1.65, 0.88, 0.925) 0s;
    outline: 0;
  "
>
  <span>No content found</span>
</button>

<button
  x-data
  x-text="'I got content!'"
  style="
    background: rgba(0, 0, 0, 0.4);
    color: #fff;
    padding: 10px 20px;
    font-size: 30px;
    border: 2px solid #fff;
    margin: 8px;
    transform: scale(0.9);
    box-shadow: 4px 4px rgba(0, 0, 0, 0.4);
    transition: transform 0.2s cubic-bezier(0.34, 1.65, 0.88, 0.925) 0s;
    outline: 0;
  "
>
  <span>No content found</span>
</button>

Context

Vue 3

<script setup>
import { ref, provide } from "vue";
import UserProfile from "./UserProfile.vue";

const user = ref({
  id: 1,
  username: "unicorn42",
  email: "unicorn42@example.com",
});

function updateUsername(username) {
  user.value.username = username;
}

provide("user", { user, updateUsername });
</script>

<template>
  <h1>Welcome back, {{ user.username }}</h1>
  <UserProfile />
</template>

Alpine

Alpine does not have a built-in context system. For sharing data between components, you would typically need to use a global state management solution or pass data through props.

Form input

Input text

Vue 3

<script setup>
import { ref } from "vue";
const text = ref("Hello World");
</script>

<template>
  <p>{{ text }}</p>
  <input v-model="text" />
</template>

Alpine

<div x-data="{ text: 'Hello World' }">
  <p x-text="text"></p>
  <input x-model="text" />
</div>

Checkbox

Vue 3

<script setup>
import { ref } from "vue";

const isAvailable = ref(true);
</script>

<template>
  <input id="is-available" v-model="isAvailable" type="checkbox" />
  <label for="is-available">Is available</label>
</template>

Alpine

<div x-data="{ isAvailable: true }">
  <input id="is-available" x-model="isAvailable" type="checkbox" />
  <label for="is-available">Is available</label>
</div>

Radio

Vue 3

<script setup>
import { ref } from "vue";

const picked = ref("red");
</script>

<template>
  <div>Picked: {{ picked }}</div>

  <input id="blue-pill" v-model="picked" type="radio" value="blue" />
  <label for="blue-pill">Blue pill</label>

  <input id="red-pill" v-model="picked" type="radio" value="red" />
  <label for="red-pill">Red pill</label>
</template>

Alpine

<div x-data="{ picked: 'red' }">
  <div>Picked: <span x-text="picked"></span></div>

  <input id="blue-pill" x-model="picked" type="radio" value="blue" />
  <label for="blue-pill">Blue pill</label>

  <input id="red-pill" x-model="picked" type="radio" value="red" />
  <label for="red-pill">Red pill</label>
</div>

Select

Vue 3

<script setup>
import { ref } from "vue";

const selectedColorId = ref(2);

const colors = [
  { id: 1, text: "red" },
  { id: 2, text: "blue" },
  { id: 3, text: "green" },
  { id: 4, text: "gray", isDisabled: true },
];
</script>

<template>
  <select v-model="selectedColorId">
    <option
      v-for="color in colors"
      :key="color.id"
      :value="color.id"
      :disabled="color.isDisabled"
    >
      {{ color.text }}
    </option>
  </select>
</template>

Alpine

<div
  x-data="{
  selectedColorId: 2,
  colors: [
    { id: 1, text: 'red' },
    { id: 2, text: 'blue' },
    { id: 3, text: 'green' },
    { id: 4, text: 'gray', isDisabled: true }
  ]
}"
>
  <select x-model.number="selectedColorId">
    <template x-for="color in colors" x-bind:key="color.id">
      <option
        x-text="color.text"
        x-bind:value="color.id"
        x-bind:disabled="!!color.isDisabled"
        x-bind:selected="color.id === selectedColorId"
      ></option>
    </template>
  </select>
</div>

Webapp features

Render app

Vue 3

<!DOCTYPE html>
<html>
  <body>
    <div id="app"></div>
    <script type="module" src="./main.js"></script>
  </body>
</html>

Alpine

<h1>Hello world</h1>

Fetch data

Vue 3

<script setup>
import useFetchUsers from "./useFetchUsers";

const { isLoading, error, data: users } = useFetchUsers();
</script>

<template>
  <p v-if="isLoading">Fetching users...</p>
  <p v-else-if="error">An error ocurred while fetching users</p>
  <ul v-else-if="users">
    <li v-for="user in users" :key="user.login.uuid">
      <img :src="user.picture.thumbnail" alt="user" />
      <p>
        {{ user.name.first }}
        {{ user.name.last }}
      </p>
    </li>
  </ul>
</template>

Alpine

<div
  x-data="
		function fetchUsers() {
			return {
				users: null,
				isLoading: false,
				error: null,
				async init() {
					this.isLoading = true;
					try {
						this.users = (await (await fetch('https://randomuser.me/api/?results=3')).json()).results;
					} catch (err) {
						this.users = [];
						this.error = err
					}
					this.isLoading = false;
				},
			};
		}
	"
>
  <template x-if="isLoading">
    <p>Loading...</p>
  </template>

  <template x-if="error">
    <p>Error fetching users</p>
  </template>
  <template x-if="!error">
    <ul>
      <template x-for="user in users">
        <li>
          <img
            :src="user.picture.thumbnail"
            :alt="`picture of ${user.name.first} ${user.name.last}`"
          />
          <p x-text="`${user.name.first} ${user.name.last}`"></p>
        </li>
      </template>
    </ul>
  </template>
</div>