Reputation: 7253
In my component I've data that is succesptible to be invalid
<template>
<p> field </p>
<p> {{ maybeInvalid }} </p>
<p> other field </p>
<template>
var component = {
data: function () {
return {
maybeInvalid: xxx
}
}
I've 3 ideas to fix that :
1 - Use v-if
v-else
in template
<template>
<p> field </p>
<p v-if="isValid(maybeInvalid)"> {{ maybeInvalid }} </p>
<p v-else> invalid </p>
<p> other field </p>
<template>
...
methods: {
isValid: function (data) {
return data != null;
}
}
2 - Make a computed value
<template>
<p> field </p>
<p> {{ computedIsValid }} </p>
<p> other field </p>
<template>
computed: {
computedIsValid: function() {
return isValid(maybeInvalid) ? maybeInvalid : "invalid";
}
}
3 - build a component
var isValidCompoenent = {
props: ['maybeInvalid'],
template: `
<p v-if="isValid(maybeInvalid)"> {{ maybeInvalid }} </p>
<p v-else> invalid </p>`
methods: {
isValid: function (data) {
return data != null;
}
}
}
and use this component
<template>
<p> field </p>
<is-valid-component :maybeInvalid="maybeInvalid" />
<p> other field </p>
<template>
...
components: {
isValidComponent: isValidComponent
}
I would like to know what's the best (more idiomatic) solution to solve that pattern
Thanks
Upvotes: 2
Views: 1704
Reputation: 82459
It's hard to choose which would be more idiomatic; these are all idiomatic solutions to your issue using Vue. In other words, I would not be unhappy to see any of them in a Vue application.
That said, I would steer away from the component solution in this case unless you are likely to use the is-valid
component in many places, not just the one component you are talking about here. Additionally, Joe Developer reading your code is not going to know right off the bat exactly what that does; they'll have to go read the code for is-valid
.
Using a computed or a v-if
are pretty much equivalent in my eyes in this case with one exception. Using the same argument above, Joe Developer reading your template is going to immediately know what happens with v-if
but will have to look at the computed to fully understand it. This, however is a very minor thing.
Upvotes: 2