vue之插槽(具名插槽)

151 阅读1分钟

插槽组件Slott.vue

<template>
  <div class="slott">
    <div v-for="(item,index) in swordRank" :key="index">
      <slot name="sword" :msg="item"></slot>
    </div>
  </div>
</template>

<script>
export default {
  name: "Slott",
  data() {
    return {
      swordRank: [
        { name: "王仙芝" }, 
        { name: "剑九黄" },
        { name: "徐凤年" },
        { name: "姜泥" },
        ]
    };
  },
};
</script>

主组件 App.vue

<template>
  <div id="app">
    <slott>
      <!-- 方法一  -->
      <h3 slot="sword" slot-scope="scope" @click="show(scope.msg.name)">
        {{ scope.msg.name }}
      </h3>

      <!-- 方法二 -->
      <!-- <template v-slot:sword="val">
        <div>
          <h3 @click="show(val.msg.name)">{{val.msg.name}}</h3>
        </div>
      </template> -->
      
    </slott>
  </div>
</template>

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

export default {
  name: "App",
  components: {
    slott,
  },
  methods: {
    show(name) {
      alert(name);
    },
  },
};
</script>

<style>
#app{
  width: 800px;
  margin: 0 auto;
  border: 1px solid burlywood;
  padding: 20px;
  margin: 20px;
  text-align: center;
}
</style>