vue functional函数式组件
阅读原文时间:2023年07月08日阅读:1

第1种写法

test.vue

<template functional>
  <div class="test">
    {{props.test.name}}
  </div>
</template>

<script>
export default {
  props: {
    test: Object,
    default: () => ({})
  }
}
</script>

父组件 index.vue

<template>
  <div>
    <test :test="{name: 'vue'}"></test>
  </div>
</template>
<script>
import test from './test'
export default {
  components: {
    test
  }
</script>

第2种写法

test.js

import Vue from 'vue'

Vue.component('test', {
  functional: true,
  props: {
    test: {
      type: Object,
      required: true
    }
  },
  render: function (createElement, context) {
    return createElement(
      'div',
      {
        attrs: {
          class: 'test'
        }
      },
      [context.props.test.name]
    )
  }
})

父组件 index.vue

<template>
  <div>
    <test :test="{name: 'vue'}"></test>
  </div>
</template>
<script>
import './test.js'
</script>