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

2

5

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>

Pumpkin answered 4/5, 2022 at 7:0 Comment(0)
K
6

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 }" />
Knickerbockers answered 4/5, 2022 at 14:43 Comment(1)
In this case w will not be reactive, because getting a value from the props in root scope of <script setup> will cause the value to lose reactivity. See vue/no-setup-props-destructure lint rule.Rendition
P
1

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

Pumpkin answered 4/5, 2022 at 7:0 Comment(2)
you can get the value by using props.widthsKnickerbockers
and instead of { widths } = toRefs(props) you could also widths = toRef(props, 'widths') getting only the desired. see toRefSanfo

© 2022 - 2024 — McMap. All rights reserved.