vue-imask
指令似乎与 Vuetify 元素不兼容,因为它期望该元素是 <input>
,但 <v-text-field>
解析为 <div>
(具有多个构成自定义输入的内部元素)。虽然文档显示了一个 example,您可以通过计算属性使用 IMask,可能绑定到任何 v-model
(可能包括 <v-text-field>
),但我无法让该示例适用于任何元素。
您可以考虑将
<v-text-field>
与不同的屏蔽库一起使用,例如 vue-the-mask
,如 Vuetify 文档中所建议。
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
</head>
<body>
<div id="app">
<v-app>
<v-content>
<v-text-field v-mask="['(###)###-####', '#-###-###-####', '###-###-####']" placeholder="Enter phone number" />
</v-content>
</v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vue-the-mask.js"></script>
<script>
Vue.use(VueTheMask)
new Vue({
el: '#app',
vuetify: new Vuetify()
})
</script>
</body>
</html>
我遇到了同样的问题,并通过使用普通依赖项将掩码注入 v-text-field 组件来修复它。
简而言之,我在哪里做了什么。在我的 HTML 部分中,我使用
ref
属性来声明我的输入来访问它
<v-text-field
ref="maskedPriceInputRef"
label="Price"
required
outlined
/>
后来在我的 JS 代码中,我声明了 ref 变量以将其附加到元素
const maskedPriceInputRef = ref(null)
const maskOptions = {
mask: Number,
scale: 2,
radix: '.',
commit: (value, masked) => {
componentState.price = value
},
}
然后,在安装组件后,我使用
watcher
来初始化掩码
watch(maskedPriceInputRef, (el) => {
if (el) {
// get the input element from vuetify, since it doesn't support vue-imask directly
const inputElement = el.$el.querySelector('input')
// init the mask
maskedPriceEl = IMask(inputElement, maskOptions)
}
})
这就是我让它发挥作用的方式。正如您所看到的,我正在使用
commit
回调来更新我的组件状态,但您完全可以使用创建的 IMask
对象。