是否可以观看注入的财产

Dov*_*fen 4 vue.js vuejs3

我正在构建一个使用 Vue 3 的应用程序,并且在父组件中提供一个属性,随后将其注入到多个子组件中。有什么方法可以让注入此属性的组件观察它的变化吗?

父组件看起来像:

<template>
  <child-component/>
  <other-child-component @client-update="update_client" />
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      client: {}
    }
  },
  methods: {
    update_client(client) {
      this.client = client
    }
  },
  provide() {
    return {
      client: this.client
    }
  },
}
</script>
Run Code Online (Sandbox Code Playgroud)

子组件如下所示:

<script>
export default {
  name: 'ChildComponent',
  inject: ['client'],
  watch: {
    client(new_client, old_client) {
      console.log('new client: ', new_client);
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

我试图实现这一点:当提供的变量在父级中更新时,注入该变量的子组件应该得到通知。由于某种原因,当客户端更新时,客户端监视方法不会被调用。

有更好的方法来实现这一点吗?

更新

经过进一步测试,我发现这里存在一个更大的问题,即使在父组件中更新了客户端后,子组件中的客户端属性仍然是原始的空对象并且不会更新。由于提供的属性是反应性的,所以它注入的所有位置都应该自动更新。

Dan*_*iel 6

更新

当使用对象 API 响应式定义 ( data(){return{client:{}}) 时,即使变量在组件内是响应式的,injected 值也将是静态的。这是因为provide将其设置为最初设置的值。要使反应性起作用,您需要将其包装在computed

provide(){
  return {client: computed(()=>this.client)}
}
Run Code Online (Sandbox Code Playgroud)

文档: https: //vuejs.org/guide/components/provide-inject.html#working-with-reactivity


您可能还需要用于deep您的手表

例子:

<script>
  export default {
    name: 'ChildComponent',
    inject: ['client'],
    watch: {
      client: {
        handler: (new_client, old_client) => {
          console.log('new client: ', new_client);
        },
        deep: true
      }
    }
  }
</script>
Run Code Online (Sandbox Code Playgroud)

  • 添加深度到手表配置没有帮助 (2认同)