[Vuejs]-How can I move a value of variable html to a file/child component vue?

0👍

<!-- footer.vue   -->

<template>
  <div>
      footer code
  </div>
</template>


   

<script>


export default {
 props:["myvalue"]
   }
</script>
 


<!-- main.vue   -->


<template>
  <div>
      <footer :myvalue="myvalue"></footer>
  </div>
</template>


<script>

import footer from "footer.vue"

export default {
  components:{footer},
  data(){
      return {
       myvalue:"data"
      }
   }
}

0👍

How I’ve read OP’s question…

When some async call completed, we need to put some HTML into some external DOM element which is not under control of the current VueJS app.

I would suggest using Portal for VueJS 3 or some 3rd Party lib providing similar functionality.

Using Portal you can inject active VueJS component into foreign DOM element. Also, you will be able to import a shared VueX store or some other state storage and react to the completion of async call in parallel with the main orchestrator component of the VueJS app.

I hope it’ll do the job…

0👍

The existing implementation looks fine. The primary thing you are trying to achieve is to move the unreadable HTML code to a separate component and mount dynamically to the current component when the date picker is opened.

It won’t work in that way.The Child component cannot be mounted into a parent datepicker component. Because,

document.querySelector('.v-date-picker-table').append(div)

The old above logic appends HTML string to a div element, datepicker component is dynamically created on the fly, you won’t have control to append another Vue component

Instead, you can store HTML string to a separate js file to make your code readable

// create a js file names utility.js(any file name to your convenient)

'use strict'
let getFooterDiv = function() {
  var div = document.createElement('div');
  var html = "<span><div style='float:left;height: 20px; width: 20px; border-radius: 10px; background-color: green;'></div></span><span style='margin-left: 10px; float: left;'>Available</span><span><div style='float:left;height: 20px; width: 20px; border-radius: 10px; background-color: black; margin-left:10px;'></div></span><span style='margin-left: 10px; float:left;'>Unavailable</span>";
  div.innerHTML = html;
  return div;
}; 
module.exports = {
  footerDiv: getFooterDiv,
}

in the above component you can import this js function and use it

    import { footerDiv } from utility;


.....

    setFooter() {
      if (!this.footer) {
        var footer = footerDiv();
        document.querySelector('.v-date-picker-table').append(footer);
        this.footer = true;
      }
    },

Now the code looks readable, and html generation is moved to a separate function instead of separate component

Leave a comment