繁体   English   中英

Vue双向数据绑定到深层嵌套数据 object

[英]Vue two-way data binding to deep nested data object

我在使用 vue v 3.0.5 对深层嵌套 object 属性进行双向数据绑定时遇到了一些问题。 我的 api 返回一个 json,然后我以这种方式将其保存到我的 vue 实例的data中:

{
...
  "ratings": [
    {
      "id": 3,
      "text": "This is some text",
      "rating": {
        "plot": 3,
        "character development": 7,
        "cinematography": 5
      },
      "createdAt": "2022-02-01T17:23:48.032Z",
      "updatedAt": "2022-02-19T09:51:18.254Z",
      "publishedAt": "2022-02-01T17:24:12.878Z"
    },...
  ]
}

现在我的模板中有一个部分用于呈现评级,将值传递给一个组件,然后该组件以 1-10 的等级显示该值。 现在我正在寻找一种方法来将rating中的这些单个值绑定到,比方说plot到我的模板中的范围输入,它看起来像这样:

<template v-for="(value, component) in movie.ratings[0].rating">
              <div class="rating__label">{{ component }} {{value}}</div>
              <input type="range" min="0" max="10" v-bind="value">             
            </template>

希望理论上它应该将enginegearbox内部rating的值绑定到 slider,所以当我更新移动 slider 时, ratings.rating内部的值得到更新。 然而,我还没有找到任何解决方案。

有人可以在这里指出我正确的方向吗? 也许更具体地说,如何在这里正确使用v-bind以使绑定起作用? 甚至可以绑定到深层嵌套的属性吗?

最好的问候derelektrischemoench

如果我理解正确的话,可能类似于以下代码片段:(您可以为输入范围更改和传递值、评级索引和属性名称创建方法,因此您可以通过这种方式对任何评级使用它)

 const app = Vue.createApp({ data() { return { movie: { title: 'Some Movie', ratings: [{"id": 3, "text": "This is some text", "rating": {"plot": 3, "character development": 7, "cinematography": 5}, "createdAt": "2022-02-01T17:23:48.032Z", "updatedAt": "2022-02-19T09:51:18.254Z", "publishedAt": "2022-02-01T17:24:12.878Z"},{"id": 4, "text": "This is some text", "rating": {"plot": 4, "character development": 8, "cinematography": 6}, "createdAt": "2022-02-01T17:23:48.032Z", "updatedAt": "2022-02-19T09:51:18.254Z", "publishedAt": "2022-02-01T17:24:12.878Z"}] } }; }, methods: { changeVal(val, idx, field) { this.movie.ratings[idx].rating[field] = val } }, }) app.mount('#demo')
 <script src="https://unpkg.com/vue@3.2.29/dist/vue.global.prod.js"></script> <div id="demo"> <h5>{{ movie.title }} - ratings</h5> <div v-for="(i, idx) in movie.ratings.length":key="idx"> <div v-for="(value, component) in movie.ratings[idx].rating":key="component"> <div class="rating__label">{{ component }} {{ value }}</div> <input type="range" min="0" max="10":value="value" @input="changeVal($event.target.value, idx, component)"> </div> <hr> </div> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM