0

I am trying to enter a conditional for v-model but it is not working can someone please tell me what's wrong?

In the template I have the exact same conditional for value that must be displayed and that works, why is it not working for v-model.

Here is a button that displays the current rating and if there is no current rating it displays 0.

<button
    type="button"
    class="rateBtn"
    @click="showRating(post.id)"
>
    {{ post.rating == null ? 0 : post.rating[0] }}
</button>

The exact same ternary operator for the following v-model gives me an error:

VueCompilerError: v-model value must be a valid JavaScript member expression.

Here is the Vue part:

<div class="ratingStars">
    <div class="rating flex">
        <div
            class="star"
            v-for="index in stars"
            :key="index"
        >
            <input
                type="radio"
                name="stars"
                :value="index"
                v-model="
                    post.rating == null ? 0 : post.rating[0]
                "
                @change="ratePost"
            /><label>☆</label>
        </div>
    </div>

Because if the button shows 0 (there isn't any ratings yet) then I get an error:

Uncaught (in promise) TypeError: post.rating is null

What is wrong with my v-model conditional please?

crawlingdev
  • 212
  • 9
  • 2
    v-models shouldn't have conditionals, v-models are for linking/modeling variable value to html input element. What are you trying to do exactly? – depperm Jan 26 '23 at 18:44
  • Ok well I read you can use a condition inside v-model https://stackoverflow.com/questions/60703994/how-do-you-conditional-bind-v-model-in-vue . As I said in my question if I do not have a condition for post.rating then I get an error post.rating is null. I still want to display the form for someone to vote for a post so I cannot do a v-if on the form otherwise it will not show – crawlingdev Jan 26 '23 at 18:49
  • that question has computed get/set, do you? can you provide relevant code – depperm Jan 26 '23 at 18:51
  • Ok that is just one there are others https://stackoverflow.com/questions/44431507/using-conditional-operators-in-v-model that just have a conditional in the v-model. I do not have a computed get/set for that value. The problem is there are many posts on the page each having its own rating so really not sure how to handle a computed get/set with that – crawlingdev Jan 26 '23 at 18:54
  • did you read the answer on that one `can't give v-model a string like you're attempting in your example.` or the second one where it's tied to `value` not v-model – depperm Jan 26 '23 at 19:32
  • yes, think about when the ternary is true, it simplifies to `v-model="0"` which is not valid. v-model must always bind itself to a variable of some sort – yoduh Jan 26 '23 at 20:25

0 Answers0