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

13

在React中,我可以像这样解构props:

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

我该如何在Vue中做同样的事情呢?我目前在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%'
    }
  }
}

React中可运行的代码片段:https://jsfiddle.net/as0p2hgw/
Vue中可运行的代码片段:https://jsfiddle.net/zsd42uve/

3个回答

9
你可以使用 v-bind 指令将一个对象的所有属性绑定为 props:
<svg>
  <circle v-bind="circle"> </circle>
</svg>

7

补充CMS的回答,因为给出的示例中它不完全适用(‘stroke-width’未正确传递,需要使用kebab-case)。为使其起作用,需要这样做:

<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>

正确!感谢您提供的额外有用信息!! - Loi Nguyen Huynh

1

因为我有些疑惑如何在使用 v-bind 解构后获取子组件中的数据,所以在这里分享一下。

父组件

<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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接