I'm about to get off work, and I use "Vue3 to encapsulate an input box"

The text remarks are not written in the blog post, the version text is too messy, the code remarks are there, be minimal but understandable! There is a pursuit, you can do it 

Subassembly: 

 

<template>
  <div>
    <input type="text" :value="modelValue" @input="iptChange" />
  </div>
</template>

<script>
export default {
  // 父传子---接受父组件数据
  props: {
    modelValue: String,
  },

  setup(props, ctx) {
    function iptChange(e) {
      // 子传父 Vue3可以通过'update:modelValue'更新父组件
    //   这句话意思其实就是将目标值e.target.value,更新,发送到父组件
      ctx.emit("update:modelValue", e.target.value);
    }
    return {
      iptChange,
    };
  },
};
</script>

<style scoped></style>

Parent component: 

 

<template>
  <div class="inputs">
    <!-- 这里需要你v-model一个值,用来展示子组件更新的数据 -->
    <!-- 不然你在子组件虽然写了update:modelValue更新,但是父组件没有展示啊 -->
    <my-input v-model="content"></my-input>
    {
   
   { content }}
  </div>
</template>

<script>
import myInput from "@/components/myInput";
// 在这里多用一个Vue3的api,不用也可以,目的为了熟悉多多练习、多多熟悉
import { ref, watchEffect } from "vue";
export default {
  name: "input",
  components: {
    myInput,
  },
  setup() {
    const content = ref("");
    watchEffect(() => {
      console.log(content.value);
    });
    return {
      content,
    };
  },
};
</script>

This is the api of vue3, which is quite detailed 

 

Colleagues say that I roll, and I take advantage of my lunch break to use "Vue3's Option API" thoroughly and proficiently.

Effect legend: 

 

 

 

Guess you like

Origin blog.csdn.net/m0_57904695/article/details/123344477