Vue 3.0 顺手的写法

2020-11-30  本文已影响0人  ShoneSingLone

Vue 3.0 提升了对TypeScript的支持,伴随着组合式API的推出,tsx的使用变得顺理成章。

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld
    msg="Welcome to Your Vue.js + TypeScript App"
    other="other"
    :sub="{ msg: 'sub' }"
  >
    <template #default="{ args }">
      <h1>Main slot {{ args }}</h1>
    </template>
    <template #sub="{ args, count }">
      <h1>Sub {{ args }} {{ count }}</h1>
    </template>
  </HelloWorld>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import HelloWorld from "./components/HelloWorld";

export default defineComponent({
  components: {
    HelloWorld
  }
});
</script>

<style lang="less"></style>

import { computed, defineComponent, reactive } from "vue";


const PrivateComponent = defineComponent({
  setup(props, { attrs }) {
    return () => {
      const sub = attrs.sub as { msg: string };
      return (
        <>
          { sub && sub.msg ? <p>{sub.msg}</p> : <h1>noting</h1>}
        </>)
    }
  }
});

export default defineComponent({
  name: "HelloWorld",
  props: {
    msg: String
  },
  data() {
    return {
      formData: {
        input: ""
      }
    }
  },
  setup(props, ctx) {
    const { attrs, slots, emit } = ctx;
    /* data */
    const state = reactive({ count: 1, msg: "state" });
    /* computed */
    const doubleCount = computed(() => state.count * 2);  /* methods */
    /* methods */
    const handleClick = () => state.count++;

    /* render */
    return () => {
      const
        Main = slots.default as any,
        Sub = slots.sub as any,
        pContent = `click count: ${state.count} computed: ${doubleCount.value}`,
        mainArgs = { msg: `main's value`, count: state.count };

      return (
        <>
          <h1>Vue 3.0 with JSX</h1>
          <input v-model={state.count} type="number" />
          <Main args={mainArgs} />
          <Sub args={`sub's value`} count={state.count} />
          <button onClick={handleClick}>click</button>
          <p>{props.msg}</p>
          <p>{pContent}</p>
          <PrivateComponent {...attrs} />
        </>
      );
    };
  }
});

上一篇下一篇

猜你喜欢

热点阅读