深入了解 Vue 组件(四)

版权声明:转载请注明出处 https://blog.csdn.net/SOALIN228/article/details/84846238

Vue中的插槽

  1. 插槽 slot 可以使我们优雅的进行 DOM 的传递,插槽更方便我们进行 DOM 的传递,使用也非常简单,而且还可以定义默认值,当不传递信息时,就显示默认内容

<child>
  <h1>hello</h1>
</child>
Vue.component('child', {
 props: ['content'],
  template: `<div>
                <p>hello</p>
                <slot>默认内容</slot>  
            </div>`
})

  1. 具名插槽,我们可以给插槽起名字,这样就可以指定插槽的显示,不然 slot 会显示组件的所有内容

<body-content>
  <div class="hander" slot='hander'>hander</div>
  <div class="footer" slot='footer'>footer</div>
</body-content>
Vue.component('body-content', {
  template: `<div>
                <slot name='hander'>
                  <h1>default header</h1>
                </slot>  
                <div class="content">content</div>  
                <slot name='footer'></slot>  
            </div>`
})

Vue中的作用域插槽

作用域插槽必须写在 template 中,通过 slot-scope 可以获得子组件中绑定了数据的 itemitem,这样在父组件中就可以调用该属性


<child>
  <template slot-scope="props">
    <h1>{{props.item}}</h1>
  </template>
</child>    
Vue.component('child', {
 data: function() {
    return {
      list: [1, 2, 3, 4]
    }
  },
  template: `<div>
                <ul>
                  <slot v-for="item of list" :item="item"></slot>
                </ul>  
            </div>`
})

动态组件与v-once指令

componentVue 中的动态组件, 通过 is 绑定数据,就可以控制要展示的数据。给静态组件加上 v-once 属性的话,在第一次渲染的时候将组件放到内存中,当第二次使用时从内存中获取,性能更高


<component :is="type"></component> 
<button @click="handleBtnClick">change</button> 
Vue.component('child-one', {
 template: '<div v-once>child-one</div>'
})

Vue.component('child-two', {
  template: '<div v-once>child-two</div>'
})

var vm = new Vue({
  el: '#root',
  data: {
    type: 'child-one'
  },
  methods: {
    handleBtnClick: function() {
      this.type = this.type === 'child-one' ? 'child-two' : 'child-one';
    }
  }
})

猜你喜欢

转载自blog.csdn.net/SOALIN228/article/details/84846238
今日推荐