Search code examples
vue.jsvuejs3tailwind-cssvue-composition-apivue-script-setup

Vue.js 3: How to get props value and use it in functions in script setup?


We all love vue 3 new script setup, but it is difficult to shift to it because of low usage and less support. I faced problem while getting and using props value inside functions.My code was like below

<script setup>
defineProps({
  text: String,
  howShow: Number,
  text1: String,
  text2: String,
  text3: String,
  widths: {
    type: String,
    default: "100%",
  },
})
</script>


Solution

  • To access the data, you can simply use: props.widths

    after defining your props in your child component:

    <script setup>
    import { computed } from 'vue'
    const props = defineProps({
      widths: {
        type: String,
        default: '100%',
      }
    })
    // do some stuff
    // access the value by 
    // let w = props.widths
    </script>
    

    in your template area you can access the value directly with widths:

    <div :style="{ width: widths }" />