首页  >  问答  >  正文

javascript - vue template 如何模拟 jsx 中的解构 props 特性

我们知道,在 jsx 中可以这样为 props 赋值

const props = {
  a: 1,
  b: 1,
}

render() {
  return (
    <MyComponent {...props} />
  )
}

在 vue 中,虽然我能够这样做

<template>
<my-comp :some-props="props"></my-comp>
</template>

// ...
data() {
  return {
    props: {
      a: 1,
      b: 1,
    },
  },
},

但和上述的区别在于,这样 my-comp 其实只接收了一个 some-props 的 prop, (一个对象属性),而不是像 jsx 那样,获得了 ab 两个 prop (值展开的属性)。

对象属性和展开属性的区别在于,前者不方便做 props 验证。

如果我想实现和 jsx 一样的效果,我就要这样写

<template>
<my-comp :a="props.a" :b="props.b"></my-comp>
</template>

// ...
data() {
  return {
    props: {
      a: 1,
      b: 1,
    },
  },
},

这样写超级烦,因为经常要写好多 prop。

那么问题来了,请问在 vue 中是否可以实现 jsx 中那样的简写呢?

PHP中文网PHP中文网2710 天前1002

全部回复(2)我来回复

  • 我想大声告诉你

    我想大声告诉你2017-05-19 10:21:07

    关注一下,另外,这样呢?

    <template>
    <my-comp :vprops="props"></my-comp> //在组件里直接用vprops.a,vprops.b
    </template>
    
    // ...
    data() {
      return {
        props: {
          a: 1,
          b: 1,
        },
      },
    },

    回复
    0
  • 習慣沉默

    習慣沉默2017-05-19 10:21:07

    那就在render函数写jsx 不要写template? 逃

    回复
    0
  • 取消回复