Skip to main content

Using Vue.render() vs calling render() from inside app with vue3

I have a product page and I got sick of putting tons of Vue code in a div with a class of hidden because a lot of the content is for modals. I found a way to render some Vue code on the fly inside of a javascript function only if the function is invoked.

The cool thing about this is I can refer to the parent app's data, when using normal Vue templates, this is not possible.

This code is not using a build step and Vue is being imported from unpkg.

In the first example I am using Vue.render() and this does work, the only thing is I found this answer from chat gpt, and I have never seen this in the docs and I could not find anything on it, but looking at unpkg, a render method is exported and available through Vue.render().

I don't know why there are no docs on this but the second example uses the render method again but inside a Vue app and there is some documentation on this.

I am wondering if anyone can explain the Vue.render() method a bit and if one approach is better than the other, and by better I mean more reliable and robust. The render method is documented and shown to be used inside an app.

Call Vue.render() and render vnode to regular DOM element without creating a new Vue app

const product_app_options = {
  data() {
    return {
      sizeOptions: [/* ... */],
      product: { /* ... */ }
    }
  },
  methods: {
    openModal() {
      const vnode = Vue.h(
            'div', 
            { 
              class: [
                'size-modal-swatches',
                'swatches'
              ]
            },
            this.sizeVariants.map(variant => 
              Vue.h(
                'button',
                {
                  class: [
                    { 
                      'soldout': !variant.available,
                      'selected': variant[product.size_option.option] === _this.selected_size
                    },
                    'pw-button',
                    'size-modal__swatch',
                    'swatch'
                  ],
                  tabIndex: 0,
                  onClick: e => _this.selectVariant(e, variant),
                  ariaLabel: variant.available 
                    ? `size ${variant[this.product.size_option.option]} available`
                    : `size ${variant[this.product.size_option.option]} not available`
                },
                [
                  Vue.h(
                    'div',
                    {
                      class: [
                        'pw-button__inner'
                      ]
                    },
                    [
                      Vue.h(
                        'span',
                        {
                          class: [
                            'size-modal__swatch-value'
                          ]
                        },
                        variant[this.product.size_option.option]
                      )
                    ]
                  )
                ]
              )
            )
          );

      // append modal to DOM
      // after appending modal grab it's content selector

      Vue.render(vnode, document.querySelector('.modal-content'))
    }
  }
}

Call render() from inside a Vue app and mount the app to a DOM element

const product_app_options = {
  data() {
    return {
      sizeOptions: [/* ... */],
      product: { /* ... */ }
    }
  },
  methods: {
    openModal() {
      const app = Vue.createApp({
        render: () => Vue.h(
            'div', 
            { 
              class: [
                'size-modal-swatches',
                'swatches'
              ]
            },
            this.sizeVariants.map(variant => 
              Vue.h(
                'button',
                {
                  class: [
                    { 
                      'soldout': !variant.available,
                      'selected': variant[product.size_option.option] === _this.selected_size
                    },
                    'pw-button',
                    'size-modal__swatch',
                    'swatch'
                  ],
                  tabIndex: 0,
                  onClick: e => _this.selectVariant(e, variant),
                  ariaLabel: variant.available 
                    ? `size ${variant[this.product.size_option.option]} available`
                    : `size ${variant[this.product.size_option.option]} not available`
                },
                [
                  Vue.h(
                    'div',
                    {
                      class: [
                        'pw-button__inner'
                      ]
                    },
                    [
                      Vue.h(
                        'span',
                        {
                          class: [
                            'size-modal__swatch-value'
                          ]
                        },
                        variant[this.product.size_option.option]
                      )
                    ]
                  )
                ]
              )
            )
          );
      })

      // append modal to DOM

      app.mount('.modal-content')
    }
  }
}
Via Active questions tagged javascript - Stack Overflow https://ift.tt/rH9ija7

Comments

Popular posts from this blog

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

The number of nodes and edges I calculated manually and by a method provided by networkx library dont match

I am trying to analyse a graph using networkx library in Python. I have implemented a function that returns the nodes and edges of that graph. After that I counted the number of nodes and edges by implementing the len() function for nodes and edges, which gave me 17 for both nodes and edges. However, when I used the method graph.number_of_nodes() of networkx library it gave me 53. My code: import pandas as pd import networkx as nx import matplotlib.pyplot as plt header_list = ["a","b","w"] E =pd.read_csv("aves-barn-swallow-contact-network.edges",sep=" ",header= None,names=header_list) # print(E.head()) # prints first few rows of the csv file G = nx.from_pandas_edgelist(E,"a","b",["w"]) nx.draw(G) plt.show() class GraphAnalyse: #finding nodes and edges def nodeEdge(self,Graph): nodes = Graph.nodes() edges = Graph.edges() ...