Reactivity

Declare state

logo of Vue 2 Vue 2

<script>
export default {
  data() {
    return {
      name: "John",
    };
  },
};
</script>

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

logo of Alpine Alpine

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

Update state

logo of Vue 2 Vue 2

<script>
export default {
  data() {
    return {
      name: "John",
    };
  },
  created() {
    this.name = "Jane";
  },
};
</script>

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

logo of Alpine Alpine

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

Computed state

logo of Vue 2 Vue 2

<script>
export default {
  data() {
    return {
      count: 10,
    };
  },
  computed: {
    doubleCount() {
      return this.count * 2;
    },
  },
};
</script>

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

logo of Alpine Alpine

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

Templating

Minimal template

logo of Vue 2 Vue 2

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

logo of Alpine Alpine

<h1>Hello world</h1>

Styling

logo of Vue 2 Vue 2

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

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

logo of Alpine Alpine

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

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

Loop

logo of Vue 2 Vue 2

<script>
export default {
  data() {
    return {
      colors: ["red", "green", "blue"],
    };
  },
};
</script>

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

logo of Alpine Alpine

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

Event click

logo of Vue 2 Vue 2

<script>
export default {
  data() {
    return {
      count: 0,
    };
  },
  methods: {
    incrementCount() {
      this.count++;
    },
  },
};
</script>

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

logo of Alpine Alpine

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

Dom ref

logo of Vue 2 Vue 2

<script>
export default {
  mounted() {
    this.$refs.inputElement.focus();
  },
};
</script>

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

logo of Alpine Alpine

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

Conditional

logo of Vue 2 Vue 2

<script>
export default {
  data() {
    return {
      TRAFFIC_LIGHTS: ["red", "orange", "green"],
      lightIndex: 0,
    };
  },
  computed: {
    light() {
      return this.TRAFFIC_LIGHTS[this.lightIndex];
    },
  },
  methods: {
    nextLight() {
      this.lightIndex = (this.lightIndex + 1) % this.TRAFFIC_LIGHTS.length;
    },
  },
};
</script>

<template>
  <div>
    <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>
  </div>
</template>

logo of Alpine 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

logo of Vue 2 Vue 2

<script>
export default {
  data() {
    return {
      pageTitle: "",
    };
  },
  mounted() {
    this.pageTitle = document.title;
  },
};
</script>

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

logo of Alpine Alpine

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

On unmount

logo of Vue 2 Vue 2

<script>
export default {
  data() {
    return {
      time: new Date().toLocaleTimeString(),
      timer: null,
    };
  },
  mounted() {
    this.timer = setInterval(() => {
      this.time = new Date().toLocaleTimeString();
    }, 1000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>

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

logo of Alpine 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

logo of Vue 2 Vue 2

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

export default {
  components: {
    UserProfile,
  },
};
</script>

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

logo of Alpine 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

logo of Vue 2 Vue 2

<script>
import AnswerButton from "./AnswerButton.vue";
export default {
  components: {
    AnswerButton,
  },
  data() {
    return {
      isHappy: true,
    };
  },
  methods: {
    onAnswerNo() {
      this.isHappy = false;
    },
    onAnswerYes() {
      this.isHappy = true;
    },
  },
};
</script>

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

logo of Alpine 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

logo of Vue 2 Vue 2

<script>
import FunnyButton from "./FunnyButton.vue";
export default {
  components: {
    FunnyButton,
  },
};
</script>

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

logo of Alpine 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

logo of Vue 2 Vue 2

<script>
import FunnyButton from "./FunnyButton.vue";
export default {
  components: {
    FunnyButton,
  },
};
</script>

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

logo of Alpine 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

logo of Vue 2 Vue 2

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

export default {
  components: { UserProfile },
  provide() {
    return {
      user: Object.assign(this.user, {
        updateUsername: this.updateUsername,
      }),
    };
  },
  data() {
    return {
      user: {
        id: 1,
        username: "unicorn42",
        email: "[email protected]",
      },
    };
  },
  methods: {
    updateUsername(newUsername) {
      this.user.username = newUsername;
    },
  },
};
</script>

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

logo of Alpine Alpine

Missing snippet Help us to improve Component Party logo

Form input

Input text

logo of Vue 2 Vue 2

<script>
export default {
  data() {
    return {
      text: "Hello World",
    };
  },
};
</script>

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

logo of Alpine Alpine

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

Checkbox

logo of Vue 2 Vue 2

<script>
export default {
  data() {
    return {
      isAvailable: true,
    };
  },
};
</script>

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

logo of Alpine Alpine

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

Radio

logo of Vue 2 Vue 2

<script>
export default {
  data() {
    return {
      picked: "red",
    };
  },
};
</script>

<template>
  <div>
    <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>
  </div>
</template>

logo of Alpine 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

logo of Vue 2 Vue 2

<script>
export default {
  data() {
    return {
      selectedColorId: 2,
      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>

logo of Alpine 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

logo of Vue 2 Vue 2

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

logo of Alpine Alpine

<h1>Hello world</h1>

Fetch data

logo of Vue 2 Vue 2

<script>
export default {
  data() {
    return {
      isLoading: false,
      error: undefined,
      users: undefined,
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    async fetchData() {
      this.isLoading = true;
      try {
        const response = await fetch("https://randomuser.me/api/?results=3");
        const { results: users } = await response.json();
        this.users = users;
        this.error = undefined;
      } catch (error) {
        this.error = error;
      } finally {
        this.users = undefined;
        this.isLoading = false;
      }
    },
  },
};
</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>

logo of Alpine 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>