vue动态组件

78 阅读1分钟

所谓动态组件: 根据数据的变化, 结合 component 标签, 随时动态切换组件的显示或隐藏

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>

  <body>
    <div id="root"></div>
  </body>
  <script>
    // 所谓动态组件: 根据数据的变化, 结合 component 标签, 随时动态切换组件的显示或隐藏
    // 根组件,用了2个子组件
    const app = Vue.createApp({
      // 变量
      data() {
        return {
          currentItem: "my-title",
        };
      },
      // 逻辑
      methods: {
        handleClick() {
          if (this.currentItem === "my-title") {
            this.currentItem = "my-input";
          } else {
            this.currentItem = "my-title";
          }
        },
      },
      // 模板
// 如果把的动态组件包到<keep-alive></keep-alive>里面,就可以保存之前组件里面的值
      template: `
			<my-input v-show="currentItem==='my-input'" />
			<my-title v-show="currentItem==='my-title'" />
            <button v-on:click="handleClick">切换</button>
            `,
            // 模板里面可以精简成<component is:"currentItem"  />
            // 如果把的动态组件包到<keep-alive></keep-alive>里面,就可以保存之前组件里面的值
            template:`
           <keep-alive>
            <component :is="currentItem" />
            
            </keep-alive>
            
            <button v-on:click="handleClick">切换</button>
        
        `
    });
    // 全局子组件
    app.component("my-input", {
      template: `
			<input type="text"/>
        `,
    });
    app.component("my-title", {
      template: `
			<h1>hello world</h1>
        `,
    });
    const vm = app.mount("#root");
  </script>
</html>