MST

星途 面试题库

面试题:Vue中组件状态管理,如何在父子组件间高效传递和更新状态?

在Vue项目里,父子组件通信场景很常见。假设父组件有一个计数器状态count,要传递给子组件显示,并在子组件中通过按钮点击实现count的增加操作,在不使用Vuex的情况下,描述实现的具体步骤和方法,包括数据绑定、事件监听以及可能用到的Vue特性。
20.4万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 父组件

    • 在父组件的data函数中定义count状态:
    <template>
      <div>
        <child-component :count="count"></child-component>
      </div>
    </template>
    
    <script>
    import ChildComponent from './ChildComponent.vue';
    
    export default {
      components: {
        ChildComponent
      },
      data() {
        return {
          count: 0
        };
      }
    };
    </script>
    
    • 通过propscount传递给子组件,这里使用了v - bind指令(:countv - bind:count的缩写)。
  2. 子组件

    • 在子组件中定义props来接收父组件传递的count
    <template>
      <div>
        <p>Count: {{ count }}</p>
        <button @click="incrementCount">Increment</button>
      </div>
    </template>
    
    <script>
    export default {
      props: ['count'],
      methods: {
        incrementCount() {
          this.$emit('count - increment');
        }
      }
    };
    </script>
    
    • 这里通过props接收count并在模板中显示。同时定义了一个按钮,点击按钮时触发incrementCount方法,该方法通过$emit触发一个自定义事件count - increment
  3. 父组件监听子组件事件

    • 在父组件中监听子组件触发的count - increment事件,并在事件处理函数中增加count的值:
    <template>
      <div>
        <child-component :count="count" @count - increment="incrementParentCount"></child-component>
      </div>
    </template>
    
    <script>
    import ChildComponent from './ChildComponent.vue';
    
    export default {
      components: {
        ChildComponent
      },
      data() {
        return {
          count: 0
        };
      },
      methods: {
        incrementParentCount() {
          this.count++;
        }
      }
    };
    </script>
    
    • 这里使用v - on指令(@count - incrementv - on:count - increment的缩写)监听子组件触发的事件,并定义incrementParentCount方法来处理该事件,在方法中增加父组件的count值。

主要用到的Vue特性有:

  • props:用于父组件向子组件传递数据。
  • $emit:子组件用于触发自定义事件。
  • v - bind:用于数据绑定,这里用于将父组件数据传递给子组件。
  • v - on:用于事件监听,这里用于父组件监听子组件触发的自定义事件。