js字元擷取與字元拼接
阿新 • • 發佈:2020-12-08
昨天寫標籤的時候碰到的,用餓了麼元件Tag的時候返回的是將陣列變成由逗號拼接的字串
<el-form-item label="" :label-width="formLabelWidth"> <el-tag v-for="tag in dynamicTags" :key="tag" style="margin-right:10px" closable :disable-transitions="false" @close="handleClose(tag)" >{{ tag }} </el-tag> <el-input v-if="inputVisible" ref="saveTagInput" v-model="mark" class="input-new-tag" size="small" :maxlength="20" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm" ><template slot="prepend"> <el-button tab-index="-1">標籤</el-button> </template> </el-input> <el-button v-else class="button-new-tag" size="small" @click="showInput" >+ 圖示標籤</el-button> </el-form-item>
dynamicTags: [],
inputVisible: false,
mark: '',
marks: ''
methods: {
handleClose(tag) {
this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
},
showInput() {
this.inputVisible = true
this.$nextTick(_ => {
this.$refs.saveTagInput.$refs.input.focus()
})
},
handleInputConfirm() {
const mark = this.mark
if (mark) {
this.dynamicTags.push(mark)
}
this.inputVisible = false
this.mark = ''
},
.................................
submitForm(formName) { this.$refs[formName].validate(valid => { if (valid) { this.loading = true if (this.dynamicTags.length <= 0) { this.$message.error('請新增圖示標籤後提交') return } this.marks = this.dynamicTags.join(',') this.form.marks = this.marks this.$request .postJSON('goods/iconStoreClouds/save', this.form) .then(res => { this.loading = false if (res.success) { this.$message({ showClose: true, message: res.message, type: 'success' }) this.clearModel() } else { this.$message.error(res.message) } }) .catch(res => { this.loading = false }) } else { return false } }) }
將陣列dynamicTags[]用逗號拼接的時候生成了一個字串marks用的是這句程式碼
this.marks = this.dynamicTags.join(',')
join() 方法用於把陣列中的所有元素放入一個字串。
元素是通過指定的分隔符進行分隔的。
而在頁面回顯的時候,要將marks重新變為陣列則需要如下處理:
// 編輯圖示資訊
editImg(id) {
this.editImgId = id;
this.$request
.get("goods/iconStoreClouds/" + id + "/update", {})
.then(res => {
if (res.success) {
this.showEdit = true;
this.form = res.content;
if (this.form.marks) {
this.dynamicTags = this.form.marks.split(",");
}
}
})
.catch(res => {});
},
split() 方法用於把一個字串分割成字串陣列。
this.dynamicTags = this.form.marks.split(",");