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

10.5k Views Asked by At

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>

2

There are 2 best solutions below

1
On BEST ANSWER

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 }" />
2
On

You can solve this problem by doing this

<script setup>
import { toRefs } from "@vue/reactivity";
const props = defineProps({
  text: String,
  howShow: Number,
  text1: String,
  text2: String,
  text3: String,
  widths: {
    type: String,
    default: "100%",
  },
})
const { widths } = toRefs(props);
let getValue = () => {
  console.log("Getting Value");
  console.log(widths.value);
};
</script>

That All Enjoy