Vue component development-solt

When using components, it is often necessary to insert some labels in the parent component for the child component. Of course, you can actually operate through attributes, etc., but it is more troublesome, and it is much more convenient to write tags directly. Then Vue provides a slot to assist child components to manage the labels written by the parent container.

When the parent container writes additional content, if the child component has exactly one slot tag, the slot tag of the child container over there will be replaced by the content written by the parent container.

For example the following example:

<!DOCTYPE html>
<<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Vue入门之extend全局方法</title>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <!--父容器输入标签-->
    <my-slot>
      <h3>这里是父容器写入的</h3>
    </my-slot>

    <!--父容器绑定数据到子容器的slot,这里的作用域是父容器的啊。-->
    <my-slot>{{ email }}</my-slot>

    <!--父容器什么都不传内容-->
    <my-slot></my-slot>
  </div>
  <script>
    // 反引号:可以定义多行字符串。
    var temp = `
      <div>
        <h1>这里是子组件</h1>
        <hr>
        <slot>slot标签会被父容器写的额外的内容替换掉,如果父容器没有写入任何东西,此标签将保留!</slot>
      </div>
    `;
    Vue.component('MySlot', {          // 如果定义的组件为MySlot,那么用组件的时候:<my-slot></my-slot>
      template: temp,
    });
    // 初始化一个Vue实例
    var app = new Vue({
      el: '#app',
      data: {
       email: '[email protected]'
      }
    });
  </script>
</body>
</html>

Final Results:

<div id="app"> <div> <h1>This is the child component</h1> <hr> <h3>This is written by the parent container</h3> </div>

<div> <h1>Subcomponent here</h1> <hr> [email protected] </div>

<div> <h1>Here is the child component</h1> The <hr> slot tag will be replaced by the extra content written by the parent container, if the parent container does not write anything, this tag will be deleted! </div> </div>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326138570&siteId=291194637