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/
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>
Because I was wondering a little bit how to get the data in child component after deconstructing with v-bind
, I will share it here.
Parent
<template>
<circle v-bind="myProp" />
</template>
<script>
export default {
data() {
return {
myProp : {
cx: '50%',
cy: '50%',
r: '45%',
strokeWidth: '10%'
}
}
}
}
</script>
circle.vue
<template>
</template>
<script>
export default {
props: {
cx: String,
cy: String,
r: String,
strokeWidth: String,
}
}
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.