Posts Learn Components Snippets Categories Tags About
/

Alpine persist plugin example

Alpine persist plugin example

Created on Jul 23, 2021

99 views

 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

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for Alpine persist plugin example

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More