Utilizing a Vue mixin to generate HTML elements and then attach them to a specified

I am looking to utilize a mixin to locate a referenced Node and then add some HTML content to it using Vue for data insertion.

const Tutorial = guide => ({
    mounted() {
        this.guide = guide;

        this.html = Vue.compile(`<p>Test</p>`).render;

        guide['add-location'].forEach(step => {
            this.$refs[step.ref].appendChild(this.html);
        })
    },
    data: function() {
        return {
            guide: null,
            html: null
        }
    }
});
export default Tutorial;

This is my current setup, where the reference gets retrieved correctly, but I'm facing issues with appending the HTML code, possibly due to incorrect usage of Vue.compile.

Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

Answer №1

In my view, it is advisable to steer clear of directly manipulating the DOM. How about substituting ref with v-html instead?

const guideTutorial = guide => ({
  mounted() {
    guide['add-location'].forEach(step => {
      this[step.ref] += this.html;
    })
  },
  data: function() {
    return {
      ...guide['add-location'].reduce((result, step) => {
        result[step.ref] = ''
        return result
      }, {}),
      html: `<p>Test</p>`
    }
  }
});

const SampleComponent = {
  template: `
    <div>
      <div v-html='foo'></div>
      <div v-html='bar'></div>
    </div>
  `,
  mixins: [guideTutorial({
    'add-location': [
      { ref: 'foo' },
      { ref: 'bar' }
    ]
  })]
}

An alternative approach is to use a wrapper component to envelop the target element or if the target is a component, then create a mixin as well.

Utilizing the html property:

<wrapper ref='foo'>
  <div>Foo</div>
</wrapper>
const Wrapper = {
  props: ['html'],
  render(h) {
    return h('div', [this.$slots.default, h('div', {
      domProps: {
        innerHTML: this.html
      }
    })])
  }
}

...

this.$refs.foo.html = '<h1>Hello Foo</h1>'

Example

Alternatively, using a custom appendChild method:

const Wrapper = {
  data: () => ({
    children: []
  }),
  methods: {
    appendChild(child) {
      this.children.push(child)
    }
  },
  render(h) {
    return h('div', [
      this.$slots.default,
      ...this.children.map(child => h('div', {
        domProps: {
          innerHTML: child
        }
      }))
    ])
  }
}

...

this.$refs.foo.appendChild('<h1>Hello Foo</h1>')
this.$refs.foo.appendChild('<h1>Hello Bar</h1>')

Example

Or utilizing Vue.compile in scenarios where the HTML content is not plain HTML:

const Wrapper = {
  data: () => ({
    template: '',
    context: {}
  }),
  methods: {
    setChild(template, context) {
      this.template = template
      this.context = context
    }
  },
  render(h) {
    let res = Vue.compile(this.template)
    return h('div', [
      this.$slots.default,
      h({
        data: () => this.context,
        render: res.render,
        staticRenderFns: res.staticRenderFns
      })
    ])
  }
}

...

this.$refs.foo.setChild('<h1>Hello {{ name }}</h1>', {
  name: 'Foo'
})

Example

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for utilizing CDN in vue cli?

My experience with packing frontend projects is limited. In the past, I only used JQuery for frontend development. Now, I have a project created by vue-cli and packed by webpack. I would like to load libraries from remote CDNs instead of my local server. ...

Instructions for showcasing a 404 error page in the event that a back-end GET request to an API fails due to the absence of a user. This guide will detail the process of separating the

I am currently working on an application that combines JavaScript with Vue.js on the front-end and PHP with Laravel on the back-end. When a GET request is made from the front-end to the back-end at URL /getSummoner/{summonerName}, another GET request is t ...

Implementing a sitemap in your VueJS project

Struggling to integrate the vue-router-sitemap library into my VueJS project, which I am building without using Vue CLI. Specifically, I want to add a sitemap.xml to my router but have hit a roadblock. After attempting to use the provided code snippets, I ...

Difficulty in efficiently organizing data for insertion into HTML elements within a Vue.js framework

My goal is to: When searching for a patient, a drop-down list appears where I can select a user and their gender and phone numbers will automatically populate in the corresponding fields. The same applies when searching for a user via their phone number. ...

Node.js equivalent of Java's byteArray

I have a Node.js REST API with images being sent from a Java application as byte arrays. Here is an image Below is the string representation of the image in byte array form: [B@c75af72 I need to decode this byte array to verify if it is indeed an ima ...

How can I adjust the scale and position of my image textures in Three.js?

Is there a way to adjust the scale and position of my image textures? The dimensions of my image are 1024px x 1024px. let textureMap = THREE.ImageUtils.loadTexture( 'texture.png' ); https://i.sstatic.net/wKd6f.jpg ...

A step-by-step guide to implementing Google Analytics Event tracking using PHP

Implementing Google Analytics Events in Javascript can be done using the following code: ga('send', 'event', 'test', 'test','value'); I am trying to incorporate this feature throughout my entire project. ...

Ending a Firestore `get` query upon unmounting component

Currently, I am retrieving data from Firestore in the componentDidMount function. However, if I happen to change the component while it is still in the process of fetching data, an error occurs: Warning: Can't call setState (or forceUpdate) on an u ...

Determine the gravitational force of a planet on falling objects and display the result in an input field

I have developed a form code that includes several dropdown menus with different options, as well as an alert popup message to prevent users from selecting the same planet more than once. Additionally, I have disabled one input in a textbox because only on ...

Error: Identifier Not Expected (Exploring Generators in ES6)

After delving into the information provided in the generators documentation on MDN, I devised a straightforward experiment: var nodes = { type: 'root', value: [ { type: 'char', value: 'a' }, { type: &ap ...

React: Updating useState array by removing the first element triggered by an event or timer

I am currently working on a function that populates a useState array containing objects representing cars. These cars appear on the left side of the screen and move across until they are off-screen. My goal is to remove these cars from the state array once ...

Is it possible to protect assets aside from JavaScript in Nodewebkit?

After coming across a post about securing the source code in a node-webkit desktop application on Stack Overflow, I began contemplating ways to safeguard my font files. Would using a snapshot approach, similar to the one mentioned in the post, be a viable ...

Implementing an API route to access a file located within the app directory in Next.js

Struggling with Nextjs has been a challenge for me. Even the most basic tasks seem to elude me. One specific issue I encountered is with an API call that should return 'Logged in' if 'Me' is entered, and display a message from mydata.tx ...

JavaScript script that parses innerHTML

Does the behavior of element.innerHTML = '<script>alert()</script>'; differ across browsers? Can I consistently expect innerHTML to not parse scripts? ...

What is the process for creating a linked TreeNode in the Ant tree design?

After completing a tree design utilizing Ant Design, I encountered an issue where certain nodes within the tree needed to act as links. Despite my attempts to directly assign links, they were not functioning properly. array.map((node) => { if(node.t ...

PHP project encountered an error stating: "Uncaught TypeError: Ajax is not a function"

I am in the process of configuring an apache server for a project using XAMPP, MySQL, and PHP 5.6 Unfortunately, it appears that there is an issue with how JavaScript has been referenced in the project, and I am unable to get it to function correctly (th ...

Iterate through a loop to remove DOM elements

I'm working on creating a loop that will be responsible for deleting DOM elements (one or more lines within an HTML table): <tr class="entireLine><input type="checkbox"></tr> <tr class="entireLine><input type="checkbox" che ...

Is it possible to utilize JavaScript for rotating and cropping a collection of images before uploading them to the gallery?

Struggling to implement file reader and croppie for local image editing (zoom / rotate / crop) before uploading. Seemingly stuck due to a potential DOM issue with the modal, unable to troubleshoot! FileReader () issues // // //create elements for image, ...

Guide on combining item costs and showing the total price using Vuejs and Vuex

I need help with writing code in vuex to pull data as a getter from Cart View. Specifically, I want to display the total price of chosen products and ensure that it is added up and displayed correctly. Any guidance on how to achieve this would be appreciat ...

Utilize JavaScript when sharing on social media to avoid the possibility of embedding the entire

This javascript code snippet is extracted from www.twitter.com (simply click to view the source code). I have reformatted it for better readability: if (window.top !== window.self) { document.write = ""; window.top.location = window.self.location; s ...