【问题标题】:Nuxtjs composition API reactive not working on nested objectNuxtjs 组合 API 反应式不适用于嵌套对象
【发布时间】:2021-11-22 21:19:40
【问题描述】:

我想更新嵌套的反应对象,root.data.name 的值。我尝试过使用 $nuxt.$set 和 Object.assign,但它们都不起作用。 我的代码如下:

<template>
 {{ root.data.name }}
</template> 
<script>
   import { defineComponent, reactive } from '@nuxtjs/composition-api'
   export default defineComponent({
       setup() {
          const root = {
             data: reactive({
                name: 'default'
             })
          }

          return {{ root }}
       }
   })
</script>

下面是我用来更新对象的代码。

1: $nuxt.$set(root, 'data', {name: 'updated name'})

2: root.data = Object.assign({}, root.data, { name: 'updated name' })

虽然值已经更新到对象,但是并没有反映到模板(html)中。

【问题讨论】:

  • 这是您拥有的实际代码吗? root 不是从设置中返回的,它没有在模板中使用
  • 不,更新了问题。谢谢
  • return {{ root }} 不是有效的语法。请提供可以重现问题的stackoverflow.com/help/mcve。此外,它也没有显示您更新对象的确切位置,这可能是问题的一部分。

标签: vue.js nuxt.js vue-composition-api


【解决方案1】:

问题在于root 本身没有反应性。

应该是:

  const root = reactive({
     data: {
        name: 'default'
     }
  })

那么root.data = ...root.data.name = ... 都会导致更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2019-09-16
    • 1970-01-01
    • 2022-12-10
    相关资源
    最近更新 更多