vue3+typescript自定義input組件


初學Vue3+ts,有不足的地方請大佬更正!!!

 

 

可以看看官網  https://v3.cn.vuejs.org/guide/component-custom-events.html#定義自定義事件

 

<template>
  <!-- 父組件 -->
  <div class="hello">
    <p>{{ text }}</p>
    <!-- v-model===v-model:modelValue -->
    <HInput v-model="text" placeholder="請輸入xxXxx"></HInput>
  </div>
</template>
// 父組件ts部分 在script上加上語言類型 <script lang='ts'>
import { defineComponent, ref } from "vue";
// 引入tsx不需要寫后綴 引入vue需要寫全文件后綴 import HInput from
"./HInput"; export default defineComponent({ components: { HInput, }, name: "HelloWorld", props: { msg: String, }, setup() { // 定義響應式數據 let text = ref(""); return { text }; }, });
// 子組件    HInput.tsx
import { defineComponent } from 'vue';

export default defineComponent({
    name: 'HInput',
    // emits已發送的事件  modelValue是默認的不可刪除 可以更改(父組件的v-model===v-model:modelValue)
    emits: ['update:modelValue'],
    props: {
        // 父組件綁定的v-model
        modelValue: {
            type: String,
            default: ''
        }
    },
    setup(props, { emit, attrs }) {
        function onInput(event: Event) {
            // 類型斷言     斷定event.target一定是html input標簽   不然不能點value
            let input = (event.target as HTMLInputElement).value
            if (props.modelValue !== input) {
                // 發送事件 此時父組件會監聽到
                emit('update:modelValue', input)
            }
        }
        return () => {
            return (
                <div>
                    <p>{props.modelValue}</p>
                    <input type="text"
                        value={props.modelValue}
                        onInput={onInput}
                        placeholder={attrs.placeholder as string}
                    />
                    {/* attrs.placeholder as string  類型斷言 斷定他一定是字符串 */}
                </div>
            );
        }
    }
})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM