我有一个帖子数组,每个帖子都有一个用户。我还有一个select字段,可以在其中更改post的用户。但是,只有用户的id在页面上更新,而不是用户名本身。我怎么能让他们都更新和反映变化?

data() {
    return {
        posts: [
            {
                id: 1,
                post_body: 'hello world',

                user: {
                    id: 45,
                    username: 'Johnny13'
                }
            },
            {
                id: 2,
                post_body: 'what is up?',

                user: {
                    id: 97,
                    username: 'Billly75'
                }
            }
        ],

        users: [
            {id: 45, username: 'Johnny13'},
            {id: 97, username: 'Billly75'}
        ]
    }
}

HTML格式
<div v-for="(post, index) in posts">
    The user for this post is:
    {{ post.user.id }} <!-- this changes -->
    {{ post.user.username }} <!-- this does not -->

    Change the post's user:
    <select v-model="post.user.id">
        <option v-for="user in users" :value="user.id">{{ user.username }}</option>
    </select>
</div>

最佳答案

您可以将user对象用作v-model,对于选项值也是如此。这样地:

<select v-model="post.user">
    <option v-for="user in users" :value="user">{{ user.username }}</option>
</select>

09-10 10:47
查看更多