Skip to content

Latest commit

 

History

History
104 lines (82 loc) · 2.67 KB

README.zh-CN.md

File metadata and controls

104 lines (82 loc) · 2.67 KB

babel-preset-vca-jsx

支持自动导入createElement as h以及setup函数式组件语法和setup中的模板refs引用

功能点

  1. JSX时自动导入createElement as h
  2. 默认只有setup()的函数式组件语法
    const Hello = (prop, ctx) => {
        const state = ref('hello world');
        return () => <h1>{state.value}</h1>;
    };
  3. setup()返回的渲染函数上使用JSX分配模板引用
    const Hello = createComponent({
        setup() {
            const root = ref(null);
            watch(() => console.log(root.value)); // <h1>...</h1>
            /*
            return () => h('h1', {
                ref: root
            }, 'hello world!');
            */
            return () => <h1 ref={root}>hello world!</h1>
        }
    });
  4. 修复 @vue/babel-sugar-v-model@1.1.2setup() 中调用 this 的问题

编译前

import { ref } from '@vue/composition-api';

const Hello = (prop, ctx) => {
    const state = ref('Hello World!');
    return () => (
        <h1>{state.value}</h1>
    );
};

编译后

import { ref, createElement as h } from '@vue/composition-api';

const Hello = {
    setup: (prop, ctx) => {
        const state = ref('Hello World!');
        return () => {
            return h('h1', state.value);
        };
    }
};

使用前提

已安装@vue/composition-api@vue/cli-plugin-babel的项目

如何使用?

  1. 安装

    npm install babel-preset-vca-jsx --save-dev
  2. 配置 babel.config.js

    module.exports = {
        presets: [
            "vca-jsx",
            "@vue/cli-plugin-babel/preset"
        ]
    };

注意

  • 这里需要区分默认的 functional组件和基于 composition-apifunctional组件的概念

    • 默认的 functional组件实质是 render函数,jsx中的简写写法如下

      const Test = ({ props, children, data, ... }) => {
          return <h1>Hello World!</h1>;
      };

      注:变量名首字母必须为大写,具体回调参数见详情

    • 基于本插件的 composition-api functional实质是 setup函数,jsx中的简写写法如下

      const Test = (props, { refs, emit, ... }) => {
          return () => <h1>Hello World!</h1>;
      };

      注:与默认functional的区别是返回了一个render函数