Home / Snippets / Alpine persist plugin example
Alpine persist plugin example cover

Alpine persist plugin example

847

3 years ago

0 comments

 Alpine persist plugin allows you to store data across page loads. This plugin is very useful when you want to store currently active tabs, filters, sorting order and etc.

Install Alpine.js Persist Plugin
You can either use the CDN or install via NPM.
<script defer src="https://unpkg.com/@alpinejs/[email protected]/dist/cdn.min.js"></script>

Using NPM / Yarn.
npm install @alpinejs/persist

yarn add @alpinejs/persist

Initialize the Plugin
From your Javascript main file, you need to include the plugin before the alpine js initialization.
// js/app.js

import Alpine from 'alpinejs'
import persist from '@alpinejs/persist'

Alpine.plugin(persist)

Alpine.start()

Use the Persist Plugin
To use the persist plugin you just have to define the data value wrapped with "$persist(x)" method.

By doing so when the user presses the increment button, the number of counts increases and it will be persisted on the browser local storage.
<div x-data="{ count: $persist(0) }">
    <button x-on:click="count++">Increment</button>

    <span x-text="count"></span>
</div>

Read More
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this