简体   繁体   English

如何像 React 中的 {...props} 一样在 Vue 中解构 props?

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

In React I can destructure props like this:在 React 中,我可以像这样解构道具:

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?我怎样才能在 Vue 中做同样的事情? My current verbose version in VueJS is like:我当前在 VueJS 中的详细版本如下:

<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/ React 中的可运行代码片段: https://jsfiddle.net/as0p2hgw/
Runable code snippet in Vue: https://jsfiddle.net/zsd42uve/ Vue中可运行的代码片段: https://jsfiddle.net/zsd42uve/

You can use the v-bind directive to bind all the properties of an object as props:您可以使用v-bind指令将对象的所有属性绑定为 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).只是为了添加到 CMS 答案,因为这对给定的示例不起作用(完全),因为“笔画宽度”未正确传递(笔画宽度需要是烤肉串)。 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.因为有点疑惑如何在使用v-bind解构后获取子组件中的数据,所以在这里分享一下。

Parent家长

<template>
  <circle v-bind="myProp" />
</template>
<script>
export default {
    data() {
        return {
          myProp : {
                cx: '50%',
                cy: '50%',
                r: '45%',
                strokeWidth: '10%'
            }
        }
    }
}
</script>

circle.vue圈子.vue

<template>

</template>
<script>

export default {
  props: {
    cx: String,
    cy: String,
    r: String,
    strokeWidth: String,
  }
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM