Javascript 在Vuejs中使用逗号作为分隔符将输入分隔为芯片
我想用逗号分隔输入值,当我按enter键时,逗号前的每个值都有自己的芯片 这是进入前的样子 以下是进入后的外观: 代码现在看起来是这样的,我似乎无法使用逗号分隔符Javascript 在Vuejs中使用逗号作为分隔符将输入分隔为芯片,javascript,vue.js,Javascript,Vue.js,我想用逗号分隔输入值,当我按enter键时,逗号前的每个值都有自己的芯片 这是进入前的样子 以下是进入后的外观: 代码现在看起来是这样的,我似乎无法使用逗号分隔符 new Vue({ el:'div', props: { set: { type: Boolean, default: true } }, data() { return { chips:[], currentInput: '' } }
new Vue({
el:'div',
props: {
set: {
type: Boolean,
default: true
}
},
data() {
return {
chips:[],
currentInput: ''
}
},
methods: {
saveChip() {
const {chips, currentInput, set} = this;
((set && chips.indexOf(currentInput) === -1) || !set) && chips.push(currentInput);
this.currentInput = '';
},
deleteChip(index) {
this.chips.splice(index, 1);
}
},
template: `
<div class="chip-container">
<div class="chip" v-for="(chip, i) of chips" :key="chip.label">
<span v-for="chip in chips.split(',')" v-text="chip"></span>
<i class="material-icons" @click="deleteChip(i)">clear</i>
</div>
<input v-model="currentInput" @keypress.enter="saveChip" >
</div>
`
})
newvue({
el:“div”,
道具:{
设置:{
类型:布尔型,
默认值:true
}
},
数据(){
返回{
芯片:[],
当前输入:“”
}
},
方法:{
saveChip(){
const{chips,currentInput,set}=this;
((set&chips.indexOf(currentInput)==-1)| |!set)&chips.push(currentInput);
this.currentInput='';
},
删除芯片(索引){
该芯片拼接(索引1);
}
},
模板:`
清楚的
`
})
这里是codepen:很难判断原始数据是否在逗号后包含空格(我想没有)。如果不是,这可能就是原因。你用“,”分开 编辑: 此代码作为chips.vue文件为我运行。我在下面添加了一些样式边框,以可视化生成的单跨元素
<template>
<div class="chip-container">
<div class="chip" v-for="(chip, i) of chips" :key="chip.label">
<span v-for="oneChip in chip.split(',')" v-text="oneChip"></span>
<i class="material-icons" @click="deleteChip(i)">clear</i>
</div>
<input v-model="currentInput" @keypress.enter="saveChip" >
</div>
</template>
<script>
export default {
props: {
set: {
type: Boolean,
default: true
}
},
data() {
return {
chips:[],
currentInput: ''
}
},
methods: {
saveChip() {
const {chips, currentInput, set} = this;
((set && chips.indexOf(currentInput) === -1) || !set) && chips.push(currentInput);
this.currentInput = '';
},
deleteChip(index) {
this.chips.splice(index, 1);
}
},
}
</script>
<style scoped>
span {
border: 1px solid red;
}
</style>
清楚的
导出默认值{
道具:{
设置:{
类型:布尔型,
默认值:true
}
},
数据(){
返回{
芯片:[],
当前输入:“”
}
},
方法:{
saveChip(){
const{chips,currentInput,set}=this;
((set&chips.indexOf(currentInput)==-1)| |!set)&chips.push(currentInput);
this.currentInput='';
},
删除芯片(索引){
该芯片拼接(索引1);
}
},
}
跨度{
边框:1px纯红;
}
我在下面的输入中填写了:
abc
abc,def,geh
它们都创建了一个新行(尾部为clear),abc、def和geh各有一个红色边框。这真是个好主意!但问题仍然存在,我无法在点击enter后获得值。那么您的for循环正确吗?您的div for在未拆分的芯片上循环,而内部span再次循环,但已拆分。。。我觉得很奇怪。如果我将行更改为
,它似乎可以正常工作。以前甚至有一个console.error条目,告诉您不要对数组调用split:)您的意思是您已更改为?t它仍然不起作用,逗号后只有一个值