vue 3 日常小记

57 阅读1分钟

一、小试 jsx

1.父组件

父组件引入子组件、事件上报处理、

<script lang="jsx">
import { reactive, ref, provide  } from 'vue';

// 引入组件 aaa
import aaa from './aaa';
export default {
  setup(props) {
    // 给 aaa 子组件添加 ref
    const aaaRef = ref();
    // state相当于data
    const state = reactive({
      age: 18,
    });
    // 数量减少操作
    function onReduceNum() {
      aaaRef.value.state.num--;
    }
    // 数量增加操作
    function onAddNum() {
      aaaRef.value.state.num++;
    }


    provide('age', state.age)
    return () => (
      <>
        <div>
           {/* 上报后的事件要用on开头,首字符大写 */}
          <aaa ref={aaaRef} onAddNum={onAddNum} age={state.age} />
          <zk-button type="primary" onclick={onReduceNum}>数量减 1</zk-button>
        </div>
      </>
    );
  },
};
</script>

2. 子组件

子组件事件上报、样式 style、class

<script lang="jsx">
import { reactive, inject } from 'vue';

export default {
  // 事件上报,把要上报的方法写在 emits 里。
  emits: ['addNum'],
  props: ['age'],
  // {expose} 为了导出子组件的数据
  setup(props, { expose, emit }) {
    let age = inject('age');

    // state相当于data
    const state = reactive({
      num: 1,
    });

    // 其他逻辑代码
    function changeNum() {
      // 子组件事件上报
      emit('addNum', 1);
    }
    // 导出子组件的数据,方便让父组件获取
    expose({ state });

    // 返回一个函数,函数再返回一段html字符串
    return () => (
      <>
        <p>数量是:{state.num}</p>
        <p style="color:red;" class="bold">年纪是:{age}</p>
        <zk-button type="outline" onclick={changeNum}>
          数量加 1
        </zk-button>
      </>
    );
  },
};
</script>

<style>
.bold {
  font-size: 40px;
}
</style>