AlbertLucianto / vue-text-highlight

Text highlighter library for Vue.js :lipstick:
https://albertlucianto.github.io/vue-text-highlight
MIT License
326 stars 35 forks source link

Render function does not reflect slot content changes #12

Closed o-3 closed 5 years ago

o-3 commented 5 years ago

Hi Albert, thanks for the great plugin!

I've encountered an issue that the component does not properly rerender on slot content changes. Demo: https://jsfiddle.net/o__3/w45jqk9f/

It looks like this this.highlights property is not getting recomputed on this.$slots.default change because this.$slots.default is not reactive. https://github.com/AlbertLucianto/vue-text-highlight/blob/f3565d6ed1bd3b405085d2218787734b538c1bed/src/components/index.vue#L29-L31

However, this.$slots.default change triggers render(h) function, so I moved around some code to come up with a workaround:

Vue.component('text-highlight', {
  extends: TextHighlight,
  data() {
    return {
      text: null,
    };
  },
  created() {
    this.updateText();
  },
  beforeUpdate() {
    this.updateText();
  },
  methods: {
    updateText() {
      const defaultSlot = this.$slots.default;
      let text;
      if (!defaultSlot) text = '';
      else if (defaultSlot[0].tag !== undefined && process.env.NODE_ENV !== 'production') {
        /* eslint-disable-next-line no-console */
        console.warn('children of <text-highlight> must be a plain string.');
        text = '';
      } else {
        text = defaultSlot[0].text;
      }
      this.text = text;
    },
  },
  computed: {
    highlights() {
      return highlightChunks(this.text || '', this.queries, this.caseSensitive);
    },
  },
});

Might not be the best solution but it seems to be working. Let me know if you need more info. Thanks!

AlbertLucianto commented 5 years ago

Hi @o-3 , thanks for raising the issue and providing the suggestion. This should be fixed in v2.0.7.