我是一個 Ruby 人,正在嘗試獲取一些 Vue 知識。在我的專案中,用戶可以styleCodes通過輸入欄位提供多個 - 每個 styleCode 用逗號分隔。我想將其存盤styleCodes在陣列中以自由計算其長度。我在下面:
<template>
<form>
<input type="text" v-model="tempStyleCodes">
</form>
<button
type="button"
@click="syncProducts"
>
Sync
</button>
</template>
<script>
export default {
name: 'SyncProducts',
data() {
return {
styleCodes: [],
tempStyleCodes: '',
}
},
computed: {
productsToSyncAmount () {
this.tempStyleCodes.split(',')
this.styleCodes.push(this.tempStyleCodes)
return this.styleCodes.length
}
},
methods: {
async syncProducts() {
let confirmationText = `Do you want to ${this.productsToSyncAmount} sync products?`
this.loadId = null
if (this.productsToSyncAmount === 0) {
ModalController.showToast('', 'Type product codes for sync first, please!', 'warning')
}
// (...) some ohter irrelevant code
},
}
}
我想我需要類似于 Ruby 方法的東西,.split(',')因為我的示例輸入代碼4321test, test, 908test產生:
styleCodes: [ "4321test, test, 908test" ]
長度會給我1個元素而不是3個。
所以期望的結果應該是:
styleCodes: [ "4321test", "test", "908test" ]
如何拆分這些值?
uj5u.com熱心網友回復:
您可以使用拆分功能:
const styleCodes = [ "4321test, test, 908test" ]
console.log(styleCodes[0].split(','))
uj5u.com熱心網友回復:
您可以使用String'split()方法,該方法可以將字串或正則運算式作為分隔符。
const codes = this.tempStyleCodes.split(/\s*,\s*/);
現在您有了一組代碼,您可以styleCodes使用's方法接受的擴展語法(請參閱瀏覽器兼容性)將它們全部推入:Arraypush()
this.styleCodes.push(...codes);
例子:
const styleCodes = [];
const tempStyleCodes = "4321test, test, 908test";
const codes = tempStyleCodes.split(/\s*,\s*/);
styleCodes.push(...codes);
console.log(styleCodes);
uj5u.com熱心網友回復:
當您使用 split 函式檢查字串的長度時,我認為您的問題不是如何拆分值,而是如何系結到它
在這種情況下,我建議使用可寫的計算值
computed: {
formattedStyleCodes {
get(){
return this.tempStyleCodes.join(",")
}
set(value){
this.tempStyleCodes = value.split(',')
}
}
},
然后您可以將其系結為
<input type="text" v-model="formattedStyleCodes ">
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/481665.html
標籤:javascript Vue.js
