simplebar icon indicating copy to clipboard operation
simplebar copied to clipboard

Vue: Directive implementation & passing options

Open kalnode opened this issue 1 year ago • 0 comments

Hello,

For using simplebar with Vue, below is an alternative way, using a Vue directive, instead of the official simplebar Vue component. Using a directive like this offers two benefits: 1. No imports are required across the app, 2. To activate the custom scrollbar, only one attribute is required directly on the thing-you-want-to-scroll, without opening/closing wrap.

IMHO, this should kind of thing should be mentioned in the docs for simplebar Vue.

Directive-way (see code):

<div v-customScrollbar>
    content
</div>

Component-wrapper-way: https://github.com/Grsmto/simplebar/tree/master/packages/simplebar-vue

<simplebar>
     <div>
         content
     </div>
</simplebar>

Both ways work just fine.

QUESTION When using the directive-method, how best to pass the simplebar options from template into directive instance? Right now I'm manually passing them, and must account for value transformation, ie string vs boolean, for instance.

QUESTION Would the instance need to be destroyed when navigating away? All of the Vue lifecycles are exposed in the directive.


Code for directive way

main.ts

import { createApp } from 'vue'
import App from '@/App.vue'
import { customScrollbar } from "./directives/customScrollbar"
const app = createApp(App)
app.directive("customScrollbar", customScrollbar)
app.mount('#app')

./directives/customScrollbar.ts

// Just use simplebar core here
import SimpleBar from 'simplebar'
import 'simplebar/dist/simplebar.css'

const customScrollbar = {
    mounted(el:HTMLElement) {
        new SimpleBar(el, { 
            // TODO: How to automatically pass options from template to the simplebar instance? For now doing below:
            autoHide: el.dataset.simplebarAutoHide === 'false' ? false : true
        })
    }
}
 
export { customScrollbar }

In some template:

<main v-customScrollbar data-simplebar-auto-hide="false"> ...

kalnode avatar Apr 17 '24 18:04 kalnode