vue中的slot插槽 父组件向子组件传html标签

97 阅读1分钟

写在子组件里面,意思是slot这个位置的html代码被写在了父组件调用子组件,并在子组件传了html代码

这样同一个子组件,因为传的内容不一样,渲染的结果也就不一样

也可以这么说,slot这个位置,内容就是父组件向子组件传的html代码

子组件可以写成单标签 也可以是双标签,因为要在子组件传html标签,

<!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>
    <style>
      div.button {
        display: inline-block;
        width: 50px;
        height: 20px;
        text-align: center;
        line-height: 20px;
        border-radius: 5px;
        background-color: olive;
        cursor: pointer;
        color: white;
      }
    </style>
  </head>

  <body>
    <div id="root"></div>
  </body>
  <script>
    // 跟组件
    const app = Vue.createApp({
      // 模板使用了子组件,两次使用的子组件传的内容不一样
      //   子组件可以写成单标签<myform />
      // 也可以是双标签,因为要在子组件传html标签,写成<myform></myform>
      template: `
			<myform>  <button> 提交 </button> </myform>
			<myform> <div class="button">提交</div></myform>
		`,
    });
    // 定义全局子组件
    app.component("myform", {
      // 子组件里面是一个input框,一个提交按钮,一个div
    //   <slot></slot>写在子组件里面,意思是slot这个位置的html代码被写在了父组件调用子组件,并在子组件传了html代码
    // 这样同一个子组件,因为传的内容不一样,渲染的结果也就不一样
    // 也可以这么说,solot这个位置,内容就是父组件向子组件传的html代码
      template: `
            <input type="text" /> 
          <slot></slot>
           

        `,
    });
    const vm = app.mount("#root");
  </script>
</html>