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

Time:05-05

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>

CodePudding user response:

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

CodePudding user response:

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 }" />
  • Related