user746461
user746461

Reputation:

Apply operation to slot

<template id="my-component">
  <div>
    <h2>My component</h2>
    <pre style="border:1px black solid"><slot></slot></pre>
  </div>
</template>

<script>
Vue.component('my-component', {
  template: '#my-component',
});

new Vue({
  el: '#app',
});
</script>

How does my-component remove blank lines in slot? I want the component to be used in the following two ways and display in the same way.

<div id="app">
  <my-component>


  Component instance 1



  </my-component>

  <my-component>Component instance 2</my-component>
</div>

This is the fiddle to play with. https://jsfiddle.net/m2spzwt0/1/

Upvotes: 0

Views: 50

Answers (1)

bcjohn
bcjohn

Reputation: 2523

You can remove blank lines by manipulating data in the $slots.default. It's work, but I don't quite sure that it's a good way to do this.

https://jsfiddle.net/3s8k4fph/

Vue.component('my-component', {
  template: '#my-component',
  mounted() {
    if(this.$slots.default)
    {
      const defaultSlot = this.$slots.default[0].elm;
      defaultSlot.textContent = defaultSlot.textContent.replace(/^(\s*[\r\n])+/g,'');

      const defaultSlot2 = this.$slots.default[this.$slots.default.length-1].elm;
      defaultSlot2.textContent = defaultSlot2.textContent.replace(/([\r\n]\s)+$/g,'');
    }
  }
});

Upvotes: 0

Related Questions