[英]How do I create a methods that map my JSON object to set properties of data object in vue.js?
[英]Binding methods that are properties of a parent object in Vue.js
我有時會遇到將方法綁定為 object 屬性而不是直接 Vue 方法的情況。 例如,而不是:
<MyInput
:formatter="currencyFormat"
:parser="currencyParser"
/>
能夠做這樣的事情會很好:
<MyInput
:formatter="formatter.currency.format"
:parser="formatter.currency.parser"
/>
...並僅從 Vue class 公開formatter
,而不是為我要綁定的每個案例編寫一個瘦包裝器方法。 這會產生很多感覺不必要的樣板。
是否有可能做到這一點? 如果是這樣,class 代碼會是什么樣子? 將帶有方法的 object 放在data
中對我來說感覺不對。
我的答案信息有限。 所以我要做很多假設。
您可以讓該方法返回一個 object 並在您的模板中執行它,或者使用一個計算的返回一個 object。 兩者都將提供您想要的功能。
這可能看起來像(這是我的假設):
<script>
export default {
/* other options */
methods: {
/* other methods */
formattter() {
const format = (value) => new Intl.NumberFormat('nl-NL', { style: 'currency', currency: 'EUR' }).format(value);
const parser = (value) => parseFloat(value);
return {
currency: {
format,
parser,
},
};
}
},
}
</script>
使用上述方法,您確實可以在模板中執行以下操作:
<MyInput
:formatter="formatter().currency.format"
:parser="formatter().currency.parser"
/>
您的 props formatter
和parser
將是兩個函數,如返回的 Object 中所定義。
為了避免更多樣板文件,您還可以執行以下操作:
<script>
export default {
/* other options */
methods: {
/* other methods */
formattter() {
const formatter = (value) => new Intl.NumberFormat('nl-NL', { style: 'currency', currency: 'EUR' }).format(value); // use the same name as your prop 'formatter'
const parser = (value) => parseFloat(value);
return {
currency: {
formatter, // use the same name as your prop 'formatter'
parser,
},
};
}
},
}
</script>
在您的模板中:
<MyInput v-bind="formatter().currency" />
這會將formatter.currency.formatter
綁定到您的formatter
屬性,它還將formatter.currency.parser
綁定到您的parser
屬性。
此外,如果您在MyInput
組件中的道具需要是值(而不是函數),並且需要解析/格式化的值是父項中的數據選項中的值:
<script>
export default {
/* other options */
data() {
return {
/* other data */
myNumberValue: '9001' // Yes. It's over 9000
}
},
methods: {
/* other methods */
formattter() {
const value = this.myNumberValue;
const formatter = new Intl.NumberFormat('nl-NL', { style: 'currency', currency: 'EUR', }).format(value);
const parser = parseFloat(value);
return {
currency: {
formatter,
parser,
},
};
},
},
};
</script>
這回答了你的問題了嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.