'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 1:[1]
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 }" />
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wittgenstein |
| Solution 2 | Ch Atif |
