Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to destructure props in Vue just like {...props} in React?

In React I can destructure props like this:

function MyComponent() {
  const myProp = {
    cx: '50%',
    cy: '50%',
    r: '45%',
    'stroke-width': '10%'
  }
  return ( 
    <svg>
      <circle {...myProp}> </circle>
    </svg>
  )
}

How can I do the same in Vue? My current verbose version in VueJS is like:

<svg>
  <circle :cx="circle.cx" :cy="circle.cy" :r="circle.r" :stroke-width="circle.strokeWidth"> </circle>
</svg>

computed: {
  circle() {
    return {
      cx: '50%',
      cy: '50%',
      r: '45%',
      strokeWidth: '10%'
    }
  }
}

Runable code snippet in React: https://jsfiddle.net/as0p2hgw/
Runable code snippet in Vue: https://jsfiddle.net/zsd42uve/

like image 302
Loi Nguyen Huynh Avatar asked Dec 06 '19 16:12

Loi Nguyen Huynh


People also ask

How do you Destructure props in Vue?

Use v-bind as kind of a “prop destructuring” instead of passing multiple object properties into a component as props. This tip originally appeared as a tweet.

Are props in Vue reactive?

Props and data are both reactive With Vue you don't need to think all that much about when the component will update itself and render new changes to the screen. This is because Vue is reactive.

How do I pass a prop to a dynamic component?

To pass props dynamically to dynamic component in Vue. js, we can check the current component being rendered in component and pass in the props accordingly. to check the value of currentComponent in the currentProps` computed property. And we return an object with the props we want to pass into the child component .

Why do we Destructure props?

Advantages of Destructuring: It improves the sustainability, readability of code. It helps to cut the amount of code used in an application. It trims the number of steps taken to access data properties. It provides components with the exact data properties.


2 Answers

You can use the v-bind directive to bind all the properties of an object as props:

<svg>
  <circle v-bind="circle"> </circle>
</svg>
like image 159
Christian C. Salvadó Avatar answered Sep 30 '22 09:09

Christian C. Salvadó


Just to add to CMS answer, as this doesn't work (completely) with the given example as 'stroke-width' isn't correctly passed (stroke width needs to be kebab-case). For this to work it needs to be:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <my-component></my-component>
</div>

<script>
  Vue.component('my-component', {
    template: `
      <svg>
        <circle v-bind="circle"> </circle>
      </svg>
    `,
    computed: {
      circle() {
        return {
          cx: '50%',
          cy: '50%',
          r: '45%',
          'stroke-width': '10%'
        }
      }
    }
  })

  new Vue({
    el: '#app'
  })
</script>
like image 40
Inch High Avatar answered Sep 30 '22 11:09

Inch High