记录一下Vue插槽的用法,以免忘记。包含默认插槽,具名插槽,作用域插槽的用法,默认插槽和具名插槽都可以是作用域插槽,本示例中三个都包含作用域。@vue/cli4.0.5
父组件test.vue

<template id='test'>
  <div class="test">
    <header v-for="info in msg" :key="info.firstName">
      <slot name="header" :data="info">
        {{info.lastName}}
      </slot>
    </header>
    <div>
      <h2>{{hi}}</h2>
      <input type="text" v-model="hi" />
    </div>
    <footer>
      <slot name="footer" :data="bean">
        {{bean.sex}}
      </slot>
    </footer>
    <main>
      <slot :data="dog">
        
      </slot>
    </main>
  </div>
</template>

<script>
export default {
  name: "test",
  data() {
    return {
      hi: this.bean,
      dog: {
        id: 1,
        name: 'hashq',
        color: 'strike'
      }
    };
  },
  props: {
    msg: [Object, Array],
    bean: [Object, Array]
  }
};
</script>

子组件About.vue

<template>
  <div class="about">
    <h1>This is an about page</h1>
      <test :msg="persons" :bean="me">
        <template v-slot:header="scope">
          <el-button>{{scope.data.firstName}}</el-button>
        </template>

        <template #footer="scope">
          <el-button>{{scope.data.name}}</el-button>
        </template>

        <template #default="scope">
          <h2>{{scope.data.color}}</h2>
        </template>
      </test>
  </div>
</template>


<script>
import test from "@/components/test.vue";

export default {
  name: "about",
  data() {
    return {
      me: {
        name: 'yxs',
        sex: 'male',
        age: 22
      },
      persons: [
        {
          firstName: "1xs",
          lastName: "y"
        },
        {
          firstName: "2xs",
          lastName: "y"
        },
        {
          firstName: "3xs",
          lastName: "y"
        }
      ]
    };
  },
  components: {
    test
  }
};
</script>
Logo

前往低代码交流专区

更多推荐