skip to Main Content

I tried to convert this code to and don’t know exactly what to do with the const. Can somebody show me the way:

setup() {
    const {
      // methods
      show, onHide, changeIndex,
      // refs
      visibleRef, indexRef, imgsRef
    } = useEasyLightbox({
      // src / src[]
      imgs: [
        'http://via.placeholder.com/250x150',
        'http://via.placeholder.com/300x150',
        'http://via.placeholder.com/350x150'
      ],
      // initial index
      initIndex: 0
    })

    return {
      visibleRef,
      indexRef,
      imgsRef,
      show,
      onHide
    }
  }

2

Answers


  1. <script setup lang="ts">
    import { useEasyLightbox } from 'path-to-useEasyLightbox' // Adjust the import path
    
    const {
      show,
      onHide,
      changeIndex,
      visibleRef,
      indexRef,
      imgsRef
    } = useEasyLightbox({
      imgs: [
        'http://via.placeholder.com/250x150',
        'http://via.placeholder.com/300x150',
        'http://via.placeholder.com/350x150'
      ],
      initIndex: 0
    })
    </script>
    
    Login or Signup to reply.
  2. Mainly,

    <script setup>
    // stuff here
    </script>
    

    is a shorhand macro for:

    export default defineComponent({
      setup() {
        // stuff here
        return {
          // things from stuff the template needs
        }
      }
    })
    

    It’s a bit more than that (it accepts imports and you have all the <script setup> goodies (defineProps, defineEmits, defineModel, etc…) but, at it’s core, it’s a way to write code in a more concise way.


    So, in your case, it should look like:

    <script setup>
    import useEasyLightbox from 'path/or/package'
    const { show, onHide, changeIndex, visibleRef, indexRef, imgsRef } =
      useEasyLightbox({
        imgs: [
          'http://via.placeholder.com/250x150',
          'http://via.placeholder.com/300x150',
          'http://via.placeholder.com/350x150'
        ],
        initIndex: 0
      })
    </script>
    

    , with optional lang="ts" param.

    Important: some things are not possible with <script setup>. Do not aim to transform all your component definitions from defineComponent() to <script setup>. Treat it as an alternate syntax and only use it where it makes things easier, more readable, cleaner.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search