返回

vue3中用函数式组件控制组件显隐的实现和原理分析

前端

  1. Vue3中函数式组件控制组件显隐

1.1 创建函数式组件

// 定义一个函数式组件
const MyComponent = (props) => {
  return (
    <div>
      <h1>{props.title}</h1>
      <p>{props.content}</p>
    </div>
  );
};

1.2 注册函数式组件

// 将函数式组件注册到Vue实例中
const app = Vue.createApp({});
app.component("my-component", MyComponent);

1.3 使用函数式组件

<!-- 在模板中使用函数式组件 -->
<my-component title="组件标题" content="组件内容" />

2. 通过函数控制组件显隐

2.1 创建一个控制组件显隐的函数

const showComponent = () => {
  // 显示组件
  document.querySelector(".my-component").style.display = "block";
};

const hideComponent = () => {
  // 隐藏组件
  document.querySelector(".my-component").style.display = "none";
};

2.2 在组件内部使用控制函数

const MyComponent = (props) => {
  // 获取控制函数
  const show = props.show;
  const hide = props.hide;

  return (
    <div>
      <h1>{props.title}</h1>
      <p>{props.content}</p>
      <button @click="show">显示组件</button>
      <button @click="hide">隐藏组件</button>
    </div>
  );
};

3. 保证单例模式

3.1 在组件外部使用控制函数

<!-- 在模板中使用函数式组件 -->
<my-component :show="showComponent" :hide="hideComponent" />

3.2 在组件内部控制显示状态

const MyComponent = (props) => {
  // 获取控制函数
  const show = props.show;
  const hide = props.hide;

  // 初始化显示状态
  let visible = false;

  // 根据显示状态控制组件显隐
  useEffect(() => {
    if (visible) {
      show();
    } else {
      hide();
    }
  }, [visible]);

  // 返回组件模板
  return (
    <div>
      <h1>{props.title}</h1>
      <p>{props.content}</p>
      <button @click={() => (visible = true)}>显示组件</button>
      <button @click={() => (visible = false)}>隐藏组件</button>
    </div>
  );
};

4. 结语

本文介绍了如何在Vue3中使用函数式组件控制组件显隐,以及如何保证单例模式。通过理解原理并参考示例代码,开发者可以轻松实现组件显隐控制。