Appearance
测试 v-model
¥Testing v-model
当编写依赖于 v-model
交互(update:modelValue
事件)的组件时,你需要处理 event
和 props
。
¥When writing components that rely on v-model
interaction (update:modelValue
event), you need to handle the event
and props
.
检查 "虚拟模型集成" 讨论 以获取一些社区解决方案。
¥Check "vmodel integration" Discussion for some community solutions.
¥Check VueJS VModel event documentation.
一个简单的例子
¥A Simple Example
这是一个简单的编辑器组件:
¥Here a simple Editor component:
js
const Editor = {
props: {
label: String,
modelValue: String
},
emits: ['update:modelValue'],
template: `<div>
<label>{{label}}</label>
<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
</div>`
}
该组件将仅充当输入组件:
¥This component will just behave as an input component:
js
const App = {
components: {
Editor
},
template: `<editor v-model="text" label="test" />`,
data(){
return {
text: 'test'
}
}
}
现在,当我们输入内容时,它将更新组件上的 text
。
¥Now when we type on the input, it will update text
on our component.
要测试此行为:
¥To test this behavior:
js
test('modelValue should be updated', async () => {
const wrapper = mount(Editor, {
props: {
modelValue: 'initialText',
'onUpdate:modelValue': (e) => wrapper.setProps({ modelValue: e })
}
})
await wrapper.find('input').setValue('test')
expect(wrapper.props('modelValue')).toBe('test')
})
多个 v-model
¥Multiple v-model
在某些情况下,我们可以有多个针对特定属性的 v-model
。
¥In some situations we can have multiple v-model
targeting specific properties.
以资金编辑器为例,我们可以有 currency
和 modelValue
属性。
¥Example an Money Editor, we can have currency
and modelValue
properties.
js
const MoneyEditor = {
template: `<div>
<input :value="currency" @input="$emit('update:currency', $event.target.value)"/>
<input :value="modelValue" type="number" @input="$emit('update:modelValue', $event.target.value)"/>
</div>`,
props: ['currency', 'modelValue'],
emits: ['update:currency', 'update:modelValue']
}
我们可以通过以下方式测试两者:
¥We can test both by:
js
test('modelValue and currency should be updated', async () => {
const wrapper = mount(MoneyEditor, {
props: {
modelValue: 'initialText',
'onUpdate:modelValue': (e) => wrapper.setProps({ modelValue: e }),
currency: '$',
'onUpdate:currency': (e) => wrapper.setProps({ currency: e })
}
})
const [currencyInput, modelValueInput] = wrapper.findAll('input')
await modelValueInput.setValue('test')
await currencyInput.setValue('£')
expect(wrapper.props('modelValue')).toBe('test')
expect(wrapper.props('currency')).toBe('£')
})