首頁  >  問答  >  主體

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 天前1007

全部回覆(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
  • 取消回覆