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/
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.
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.
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 .
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.
You can use the v-bind
directive to bind all the properties of an object as props:
<svg>
<circle v-bind="circle"> </circle>
</svg>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With