How to Retrieve Component HTML Output in Vue beyond the Template Tag?

Is there a way to access the output of a component, such as ComponentName, outside of the template in Vue.js? For example, in data, methods, or during the mounted lifecycle hook.

For instance, consider a Vue file named components/Test.vue:

<template>
    <div>I'm a test</div>
</template>

In another Vue file called pages/ViewTest.vue:

import Test from '~/components/Test.vue'
export default {
    components: {Test},
    data() {
        return {
            test: Test
        }
    },
    mounted: function()  {
      console.log( Test ) // Output is Test Component Object
      console.log( this.test ) // Output is Test Component Object
    }
}

The object logged in the console seems to contain a lot of information, including a render property. However, trying to access Test.render() results in an error.

So, how can we retrieve the HTML content (e.g.,

<div>I'm a test</div>
) of a component from outside the template?

Any help or guidance would be appreciated.

EDIT

I am using the vue-material-design-icons package for SVG icons generation:

<template>
  <MapMarkerRadius/>
</template>
<script>
  import MapMarkerRadius from 'vue-material-design-icons/MapMarkerRadius'
  export default {
    components: {MapMarkerRadius}
  }
</script>

However, I encounter an issue when using a component that generates HTML:

<template>
  <div :class="'card'">
    <div v-if="title" :class="'card-title'">
      {{ title }}
    </div> 
    <div :class="'card-content'">
      <slot />
    </div>
  </div>
</template>
<script>
export default {
  name: 'card',
  props: {
    title: {},
  }
};
</script>

When using the card component with a different Vue file:

<template>
  <card :title="'Title ' + MapMarkerRadius">
    Test Content
  </card>
</template>

<script>
import card from '~/components/Card'
import MapMarkerRadius from 'vue-material-design-icons/MapMarkerRadius'
export default {
  components: {card, MapMarkerRadius}
};
</script>

The issue arises when displaying the card title, which appears as Title [object].

Answer №1

For the Test component, try implementing the use of ref by placing it in the root element:

<template>
  <div ref="test">This is a test</div>
</template>

In another component, you can then access this as follows:

   mounted: function()  {
      console.log( this.$refs.test )
    }

No need to import the component.

Answer №2

The repository you are currently utilizing consists of single-file components that generate HTML through a single tag.

import MapMarkerRadius from 'vue-material-design-icons/MapMarkerRadius'

By importing the above, you can then use it in your template as <map-marker-radius/>

This is why when appending the string title and an object such as "My Icon"+MapMarkerRadius, it results in the literal [object] being displayed like this: "My Icon [object]"

You have three options to achieve what you desire:

  1. Explore other repositories that offer easier ways to incorporate material icons.
  2. If you have access to the card component, you can utilize the class names from this repository instead of the SVG version or its component form. Add these class names to the props and include them in your component:
<card :title="'Title'" :icon_class="map-marker-radius">
    Test Content
</card>
<div v-if="title" :class="'card-title'">
      {{ title }} <div :class="icon_class"></div>
</div>
props: {
    title: {},
    icon_class: '',
}
  1. You can directly use the MapMarkerRadius component within the card component but it will only appear when certain criteria are met on the card component, for example:

main.vue

<template>
  <card :title="'Title'" :icon="true" :icon_typename="'map-marker-radius'">
    Test Content
  </card>
</template>

<script>
import card from '~/components/Card'
export default {
  components: {card}
};
</script>

with icon_typename being any name or keyword you wish to use.

card.vue

<template>
  <div :class="'card'">
    <div v-if="title" :class="'card-title'">
      {{ title }} <span v-if="icon_mmr"><map-marker-radius/></span>
    </div> 
    <div :class="'card-content'">
      <slot />
    </div>
  </div>
</template>
<script>
import MapMarkerRadius from 'vue-material-design-icons/MapMarkerRadius'
export default {
  name: 'card',
  props: {
    title: {},
    icon: { default: false },
    icon_typename: '',
    icon_mmr: false,
  },
  mounted(){
    if (this.icon && this.icon_typename === 'map-marker-radius') this.icon_mmr = true
},
  components: { MapMarkerRadius },
};
</script>

The code may not be perfect, but you can work from here and further optimize it.

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

Using JQuery to Retrieve JSON Data from an HTTPS Endpoint

I am attempting to retrieve a JSON file from an https secured website without using server-side languages. The client specifically requested that the process be entirely implemented in JavaScript. After some research, I discovered that I need to utilize J ...

Syntax of the Vue.js application object model

Just delving into the world of vue.js and stumbled upon this code snippet. Curious to know more about its structure. const CounterApp = { data() { return { counter: 0 } }, mounted() { setInterval(() => { this.counter++ ...

Devising a method to display configurable products as related items along with their customizable options in Magento

I am in the process of creating an e-commerce website using Magento for a client. The issue I am facing is that when I include a configurable product as a related item, it displays the product but without a checkbox. From what I have researched, Magento do ...

The issue with AngularJS ng-show and $timeout functionality not functioning as expected

As a newcomer to AngularJS, I recently started an individual project utilizing ng-show and if else statements with $timeout. Despite my efforts, I have been unable to make the answers timeout after being displayed for a few seconds. I've tried various ...

JavaScript code that triggers when a checkbox is not selected

I'm attempting to dynamically add an input field when a checkbox is clicked, with the intention of having the checkbox already checked by default. However, I am encountering an issue where the checkbox remains unchecked even after the input field is d ...

Access the OpenWeatherMap API to retrieve the weather forecast for a single time slot within a 5-day period

Utilizing the openweathermap api, I am retrieving a 5-day/3-hour forecast here. The API call provides multiple results for each day with data available every 3 hours. For the full JSON response, you can access it here. Please note that the API key is only ...

Error encountered when attempting to convert a JSON object to a String using JSON.stringify(), due to a cyclic object value

I have a JSON object with the following structure: obj { name: "abc" , entriesList : "list of entry obj" , propertiesList : "list of properties obj" }; In this structure, an entry is also another object entry { info : "data obj" , ...

Transmit information using $broadcast when a button is clicked, and retrieve that information using $scope.$on

I am trying to create a function that will broadcast data from the server upon button click, and then navigate to a new route using $state.go('new-route'). In the controller of this new state, I want to retrieve the transmitted data. However, whe ...

How can HTML and CSS be linked to display images independently?

Check out this code: body{ background-image:url('http://wallpoper.com/images/00/31/33/51/black-background_00313351.jpg'); } div.header{ background-color:#F0F8FF; text-align:center; padding:3px; ...

What is the method to assign a value to ng-class in Angularjs?

I need to categorize items in a list by assigning them classes such as items-count-1, items-count-2, items-count-3, items-count-4, based on the total number of items present. This is how I would like it to appear: li(ng-repeat="area in areas", ng-class=" ...

Trouble with Bootstrap modal implementation when using ajax and looping through data

I am having an issue with using the BS modal to display a form containing a select box and updating records in the database via an ajax call. The trigger button to open the modal consists of <i></i> tags with the same class name, itagbtn, and d ...

Vue.js tutorial: Adding a question mark to the URL when submitting a login form

There have been some strange issues with my login form recently. It initially directs me to However, when I try to log in, instead of logging me in, it redirects me to: I can only successfully log in after clicking on the login button again. What could ...

Utilize the functionality of the acuityscheduling API to streamline your

I've experimented with various methods but haven't had any success. Hopefully, you guys can share some insight. I'm utilizing acuityscheduling's API to fetch appointments. According to their documentation, the process should look someth ...

Error in Vue component when setting the background image URL

Here is my code snippet that sets the background image for a component: style() { return { "background-image": `url(${require(`../../../assets/images/${this .last_result}.png`)})` }; }, The expected URL should be ../../../assets/images/ ...

There are a total of 152 issues found in the index.tsx file within the react

Despite everything working correctly, I am continuously encountering these errors. Is this a common occurrence? What steps can I take to resolve them? I have developed my react application using Javascript instead of Typescript; however, I don't belie ...

Change the WordPress Divi Builder nav bar to switch from transparent to white when scrolling or upon reaching a specific point on the page

Currently, I am in the process of revamping our company's WordPress website using the Divi Builder. For the past couple of days, I have been scouring the internet trying to find a solution that would allow the navigation bar to change CSS classes as t ...

Scroll-triggered closing of modals in Next Js

I have integrated a Modal component into my Next.JS application, and I have implemented a functionality to close the modal when the user scrolls outside of it. However, this effect is also triggering when the user scrolls inside the modal. How can I modi ...

Unable to establish a hyperlink to specific section of page using MUI 5 Drawer

When attempting to link to a specific part of my first page upon clicking the Shop button in the navigation Drawer, nothing happens: https://i.stack.imgur.com/FUQCp.png This snippet shows the code for the MUI 5 Drawer component: <Drawer anch ...

Retrieving a property of an object within a function

I'm facing an issue where I am trying to access the properties of objects inside an array in my code to display text values in input boxes that are recovered from local storage after a refresh. However, when I attempt to run a for loop within my appSt ...

Leveraging Vue.js to direct users to the edit.blade.php file within resource controllers, allowing them to use the GET

Exploring the possibility of transforming an anchor tag button into a component housing the /profile/{{$user->id}}/edit path within a Laravel application for user profile editing. Is it feasible to use Vue.js in dynamically altering the URL path? We h ...