1. 程式人生 > 其它 >記錄vue3的v-model的實現方式

記錄vue3的v-model的實現方式

技術標籤:Vuevue3v-model

vue3還是有些不同的噢

<template>
  <div>
    <p>state: a: {{ state.a }}</p>
    <p>state.a(toRef): a: {{ xxx }}</p>
    <p>state.a(ref): a: {{ xxxx }}</p>

    <button @click="update1">toRef更新a</button>
    <button @click="update2">ref更新a</button>

    <!-- v-model:xxxx指定雙向繫結的變數,仍然還是之前那個語法糖 -->
    <ChildCom v-model:xxxx="xxx" />
  </div>
</template>

<script lang='ts'>
import { defineComponent, reactive, toRef, ref, h } from "vue";

export default defineComponent({
  name: "9_toRef",
  components: {
    // 定義一個子元件
    ChildCom: defineComponent({
      props: {
        xxxx: {
          type: Number,
          require: true,
        },
      },
      data() {
        return {
          a: "it worked"
        };
      },
      setup(props, context) {
        const xv = ref(props.xxxx === undefined ? 0 : props.xxxx);
        // v-model 在vue3的寫法
        const update = () => {
          console.log('update:xxxx');
          context.emit('update:xxxx', ++ xv.value);
        };
        return {xv, update}
      },
      // jsx 渲染這個元件
      render() {
        return h("div", [
          h(
            "button",
            {
              // 這裡和vue2是不一樣的
              onClick: this.update
            },
            "子元件更新值"
          ),
          h("h1", this.xv + "---" + this.a),
        ]);
      },
    }),
  },
  setup() {
    const state = reactive({
      a: 1,
    });
    // 修改toRef的值會同步更新state
    const xxx = toRef(state, "a");
    // 但是修改ref的值並不會同步更新state!
    const xxxx = ref(state.a);

    const update1 = () => {
      xxx.value++;
    };
    const update2 = () => {
      xxxx.value++;
    };

    return {
      state,
      update1,
      update2,
      xxx,
      xxxx,
    };
  },
});
</script>

<style>
</style>

一切盡在程式碼中。