A
A
Anton B2021-08-04 15:52:39
Vue.js
Anton B, 2021-08-04 15:52:39

How to turn a string from a back into a component?

Hello!

There is a chat, messages come from the server.

Each message goes to a component. Some messages come with bb-tags that need to be processed. For example, "You got 10 [ico=1]", can be converted by a simple substitution into<v-msg :content="message" />


Вы получили 10 <img src="..." v-tooltip="'золото'">

As a result, the user sees a message in which there is a gold icon, but the tooltip does not work on hover, because the v-tooltip directive was not processed.

Question : how cheap (in terms of performance and code) to make voi process the directive?

Message component code
<template> 
  <div
    class="v-msg"
    v-html="html"
  />
</template>

<script lang="ts">

import Vue from 'vue'
import BB from '@/services/bb'

export default Vue.extend({
  name: 'VMsg',

  props: {
    content: {
      type: String,
      required: true,
    },
  },

  computed: {
    html() {          
      return BB.parse(this.content)
    },
  },
})
</script>

Thanks for answers.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Yarkov, 2021-08-04
@yarkov Vue.js

https://www.npmjs.com/package/vue-runtime-template...

S
Sergey Sokolov, 2021-08-04
@sergiks

If the messages that require the rendering of components are known in advance, then you can prepare for each component, and send the data not in text, but in JSON'om def. structures. This, of course, is a crutch, but without additional dependencies.
JSON came, and in it the name of the component and data for it - we show the component. Otherwise text.

A
Alexander Medvedev, 2021-08-05
@lifestar

In vue3 you can do it like this:

<template>
    <component :is="html"/>
</template>

<script>
import { defineComponent} from 'vue';
...
this.html = defineComponent({
  template: this.content,
});
</script>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question