MST

星途 面试题库

面试题:Vue计算属性中依赖注入的基本实现方式

在Vue中,如何在计算属性里实现简单的依赖注入?请举例说明,假设存在一个父组件和子组件,父组件有一个数据属性需要注入到子组件的计算属性中。
33.3万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 父组件(Parent.vue
    <template>
      <div>
        <ChildComponent />
      </div>
    </template>
    
    <script>
    import ChildComponent from './ChildComponent.vue';
    
    export default {
      components: {
        ChildComponent
      },
      data() {
        return {
          parentData: '这是父组件的数据'
        };
      }
    };
    </script>
    
  2. 子组件(ChildComponent.vue
    <template>
      <div>
        <p>计算属性依赖注入的值: {{ computedValue }}</p>
      </div>
    </template>
    
    <script>
    export default {
      inject: ['parentData'],
      computed: {
        computedValue() {
          return this.parentData + ',经过子组件计算属性处理';
        }
      }
    };
    </script>
    

在上述例子中,父组件定义了 parentData 数据属性。子组件通过 inject 选项注入 parentData,然后在计算属性 computedValue 中使用注入的数据进行简单处理,实现了在计算属性里的依赖注入。