Is it possible to export multiple objects from a single Vue.js component?

I'm curious if it's possible to export two different objects from a Vue.js component so that other components can choose which one to use.

Here's the scenario I'm currently working on:

AboutFooBar.vue:

<template>
  <span>{{ text }}</span>
</template>

<script>
  export default {
    name: 'Foo',
    data: () => {
      return {
        text: 'foo'
      }
    }
  }
  const Bar = {
    name: 'Bar',
    data: () => {
      return {
        text: 'bar'
      }
    }
  }
  export { Bar }
</script>

Then I proceed to import both Foo and Bar in About.vue:

<template>
  <div class="about">
    <h1>This is the about page</h1>
    <Foo /><br/>
    <Bar />
  </div>
</template>

<script>
  import Foo from './AboutFooBar'
  import { Bar } from './AboutFooBar'

  export default {
    name: 'About',
    components: {
      Foo,
      Bar
    },
    data: () => {
      return {

      }
    }
  }
</script>

What I was anticipating to see displayed on the page is:

This is the about page
Foo
Bar

...but instead, only Foo is being displayed. It seems like Bar is not recognized. I had hoped to be able to provide a choice of which object to import, with the data of each object determining what populates the template (displaying 'foo' for component Foo and 'bar' for component Bar).

Is there a solution to achieve this? Thank you.

Answer №1

In my opinion, it is highly unlikely that this coding pattern is effective. Components should be streamlined, encapsulated properly, and easy to read.

If, in a scenario like the one provided where Foo and Bar share similarities, they should ideally be combined into a single component and then called twice with different props each time. Conversely, if they are distinct from each other, separate components should be created for them.

However, to address your query: Vue loader necessitates the default export to contain the component. This requirement explains the behavior you've observed.

Others have raised similar concerns, prompting a response from Evan You (the creator of Vue) in this feature request. I'll also share his insights here:

The component must be exported as the default. This is non-negotiable.

Various functionalities such as hot module replacement, CSS injection, scoped CSS, and SSR critical CSS collection rely on identifying the exported component accurately - these features would not work if the component can be exported under any arbitrary name. Additionally, certain tools (like ESLint plugin) assume that the component is the default export.

TL;DR: The default export must be the component, and this policy will remain unchanged.

Answer №2

One approach to segmenting AboutFooBar.vue into AboutFoo.vue and AboutBar.vue may seem redundant, as they are nearly identical. Would you consider utilizing props instead?

child.vue:

<template>
  <span>{{ text }}</span>
</template>

<script>
  export default {
    name: 'Child',
    props: {
      msg: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        text: this.msg
      }
    }
  }
}
</script>

About.vue:

<template>
  <div class="about">
    <h1>This is the about page</h1>
    <Child :msg="Foo" /><br/>
    <Child :msg="Bar" />
  </div>
</template>

<script>
  import Child from './Child'

  export default {
    name: 'About',
    components: {
      Child
    }
  }
</script>

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

Iterating through the array and examining each object

I have a specific structure that I'm working with. In React, I am trying to extract the Internal value from this data. My idea is to create an array of values such as ['Bitcoin', 'Etherium'...] and then map through it. Can someone ...

I seem to have misplaced my installed packages within the node_modules directory

During my project, I utilized git where the node_modules folder was naturally ignored. While working on branch1, I added some dependencies (such as redux) and installed them using npm install. Later, I switched to branch2, which was created at the same tim ...

React - Stopping the Submit Action

Recently, I have been delving into React development. In my exploration, I have incorporated the Reactstrap framework into my project. However, I have encountered an issue where the HTML form submits when a button is clicked. Is there a way to prevent this ...

A guide on how to resume and upload files using the tus-client protocol

Is there a way to implement pause and resume functionality for file uploads similar to the example shown at ? I am currently utilizing the tus-js-client Plugin available at https://github.com/tus/tus-js-client I have extensively searched for a solution w ...

Vue component experiencing issues with parent attributes not functioning correctly

I am facing an issue while building a component in Vue. When I try to add attributes like id and class, they do not appear in the rendered code. Is this the default behavior? Component <template> <input type="text" name="hello& ...

Implement a sleek carousel within a Vue component

Hello, I am trying to add a single slick carousel component to a block that already contains 2 components in a template. However, when I do this, it distorts the images of the other component. <template v-if="isMobile"> <vue-slic ...

"Enhance your audio experience across all browsers with the revolutionary

I am looking for a way to play an mp3 file endlessly when the user opens my website. I need a lightweight crossbrowser solution that works in all browsers, including IE. Any suggestions? ...

Unable to Render Image with MEAN Stack

Currently, I am utilizing the MEAN stack and attempting to exhibit an image that is stored in my Mongo database. From what I can ascertain, the image is properly saved and transmitted to the browser since the Web Console shows the image in the Response Bod ...

Encountering a socket.io error in vue-cli with an Uncaught TypeError: exists function not found

I have recently integrated socket.io into my vue-cli project using npm and am using it as shown below: import socketio from 'socket.io'; import VueSocketIO from 'vue-socket.io'; export const SocketInstance = socketio(MY_URL); Vue.use( ...

When working with jQuery, I encountered the error message "is not a function" because I mistakenly tried to use a function more than

While working on a pager, I encountered an issue with a function that is initially invoked when the document loads. However, when attempting to use it a second time, an error "is not a function" occurs. I am curious about the reason behind this phenomenon. ...

Inquiry regarding delays in updating and retrieving data with Mongoose in Node.js

I recently faced an issue related to the CRUD development process. Whenever I update a property and check the response in Postman, it always shows the previous data. For instance, after clicking send on Postman, it shows "weeks" : "11" instead of "10". Che ...

Bootstrap-vue is designed to seamlessly integrate with Vue.js, however, it seems to be experiencing some issues

click here for image description There is an error: Uncaught TypeError: Cannot read property 'prototype' of undefined at eval (config.js?228e:6) at Module../node_modules/bootstrap-vue/esm/utils/config.js (chunk-vendors.js:6778) at webpack_requir ...

Enhancing the Efficiency of Android Programming

For my application, I am currently displaying 12 markers on a map, each of which triggers a dialog box showing the location's address when tapped. However, I believe there is a more efficient way to handle this. I have been experimenting with creating ...

Execute Babel task individually for each file instead of running it on the entire directory, Grunt

I've set up a Grunfile to monitor .js files in the src/ directory and trigger the babel task from https://github.com/babel/grunt-babel to generate ES5 files in the dist/ directory: module.exports = function(grunt) { require('load-grunt-task ...

When using PHP files to send data through AJAX, be cautious of receiving only a "parsererror" message

After consulting with @skobaljic during a teamviewer session, it was discovered that I was not properly opening the html file in localhost, instead using the file system (file://...). I apologize for the confusion and time wasted. I am attempting to send ...

Tips on enhancing an array by separating values with vertical bars instead of commas

I am trying to store checked values in an array and separate them with vertical bars instead of commas. Is there a way to achieve this using the jQuery map .get() function? Any suggestions or links you can provide would be greatly appreciated. Thank you in ...

The image tag in HTML is unable to display as an image within the jQuery object

After converting the object "suggestion" to a string, I have data stored in the "sugestion" variable like this: {"value":"<img src=\"http://localhost/erp/assets/images/product/123.jpg\"> 123123123 t-shirt","data":"ABC098765"} Unfortunatel ...

Using VueJS to Modify the Accessibility of Individual Inputs within a v-for Loop

I'm facing a challenge with enabling/disabling specific inputs on button click. The issue is that when I click the button, all inputs get enabled/disabled instead of just targeting one. My code uses props called "articles" which provide the ID, title ...

What is the best way to summon two models within a single controller using Node's Express JS?

I am a beginner in Node.js and I am using the Express JS framework with the MVC pattern. My goal is to retrieve data from two different tables (using two separate functions in the model) within a single controller function. Is it possible to achieve this? ...

Generating a collection of model objects using Javascript

I want to generate a JavaScript list of my model. I am currently working on an ASP.NET MVC app The model 'testModel' looks like this: public string prop1{ get; set; } public string prop2{ get; set; } public string prop3{ get; set; } ...