用到的技術
- 父組件向子組件的傳值
類型檢查和默認值:您可以為props指定類型檢查和默認值。這可以確保傳遞給子組件的數(shù)據(jù)符合期望的類型,以及在沒有傳遞數(shù)據(jù)時具有合理的默認值。例如:
props: {
message: {
type: String,
default: 'Default Message'
},
count: {
type: Number,
default: 0
}
}
在上述示例中,message 的默認值是字符串 'Default Message',count 的默認值是數(shù)字 0。
標簽組件的效果如下
文章來源:http://www.zghlxwxcb.cn/news/detail-710148.html
封裝代碼
<template>
<div>
<el-row>
<el-input
v-model="inputText"
type="text"
@input="checkForSpace"
@keydown.enter="addTag"
/>
</el-row>
<el-row>
<div class="tags" style="margin-top:5px;">
<div
v-for="(tag, index) in tags"
:key="index"
class="tag"
>
{{ tag }}
<span class="close" @click="removeTag(index)">×</span>
</div>
</div>
</el-row>
</div>
</template>
<script>
export default {
name: "InputTag",
props: {dic: {type: Array, default: []}},
data() {
return {
inputText: '',
tags: [],
};
},created() {
this.tags = this.dic || [];//關鍵字初始化,dic的值來自于父組件(調用它的組件叫父組件)
},
methods: {
addTag() {
if (this.inputText.trim() !== '') {
this.tags.push(this.inputText);
this.inputText = '';
}
},
removeTag(index) {
this.tags.splice(index, 1);
},
checkForSpace() {
if (this.inputText.endsWith(' ')) {
this.addTag();
}
},
},
};
</script>
<style>
.tags {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.tag {
background: #ddd;
padding: 4px;
border-radius: 4px;
}
.close {
margin-left: 4px;
cursor: pointer;
}
</style>
使用代碼
<el-form-item label="文章關鍵詞" prop="kcUsername">
<InputTag v-model="form.keyword" placeholder="文章關系詞" :dic="form.keyword" />
</el-form-item>
:dic是子組件里定義的,初始化字典用的,比如在修改信息頁面,需要把之前的庫里存儲的信息加載到關鍵字標簽里,提交表單后,我們的form.keyword將獲取你輸入的字符串數(shù)組。文章來源地址http://www.zghlxwxcb.cn/news/detail-710148.html
到了這里,關于vue~封裝一個文本框標簽組件的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!