Vue3 JSX 写法笔记

Vue3 是可以用 JSX 语法直接写的, 大体可以从 https://sfc.vuejs.org/ 的示例看到,
其中

会编译为 h('div'), 具体参考 https://vuejs.org/guide/extra... .
完整的组件定义形如:

import { defineComponent, PropType } from 'vue';
import { onMounted, ref, watch } from 'vue';

const App = defineComponent({
  name: "App"
  props: {
    appId: {
      type: String as PropType,
      default: '',
    },
  },
  emits: [],
  setup(props, {emit, expose, slots}) {

    return () => (
      
TODO
); }, }); export default App;

其中

  • name 调试中组件的名字,
  • props 需要用这样的写法用 Object 格式传入,
  • emits 可以用字符串格式制定实践, 而 emit 函数从参数中拿到,
  • slots 也是从参数当中拿到,
  • expose 也是从参数当中得到的,
  • 注意最终的 render 函数, 范围与 setup 函数有区别,
    其中 setup 函数只会被执行一次, 而 render 函数可能多次执行.
    而需要响应式追踪的逻辑, 需要写在 setup 函数里边, 否则行为不能达到预期,

有了 JSX, 原有的 v-if v-else 可以和 React 异样直接写了,

{!!a ? true : null}

v-model 较为特殊, 转换后需要手动绑得 modelValue 的行为:

 a.value = v} />

v-slots 用法比较复杂, 参考 https://github.com/vuejs/babe... :

const A = (props, { slots }) => (
  <>
    

{ slots.default ? slots.default() : 'foo' }

{ slots.bar?.() }

);

expose 的用法, 传入一个对象, 参考 https://www.vuemastery.com/bl...

expose({ reset })

TODO

你可能感兴趣的:(vue3jsx)