Understanding how to display a component within another component in Vue.js

I am faced with a scenario where I have a component that has the following template:

<div v-for:"item in store" v-bind:key="item.type">
   <a>{{item.type}}</a>
</div>

Additionally, I have another component named 'StoreComponent'. The requirement is to clear the current component upon clicking an element in the first component and display the StoreComponent. Furthermore, I need to be able to pass the item.type value to the StoreComponent when this transition occurs.

To achieve this functionality, I am looking for a solution that does not involve using router-link or router.push methods as I do not wish to create a new URL. Instead, my preferred approach is to override the current component with the new one based on the item.type value.

Below is the code snippet for the StoreComponent (StoreComponent.vue):

export default{
    name: 'StoreComponent',
    props: ['item'],
    data: function () {
        return {
            datum: this.item
        }
    },
    methods: {
        //custom methods
    }
}

Answer №1

You have the option to utilize dynamic components and send the item-type as a prop.

Vue.component('foo', {
  name: 'foo',
  template: '#foo'
});

Vue.component('bar', {
  name: 'bar',
  template: '#bar',
  props: ['test']
}); 

new Vue({
  el: "#app",
  data: {
    theComponent: 'foo',  // represents the current component by its 'name'
    somethingWeWantToPass: {
        test: 123 // the prop value we want to pass
    },
  },
  methods: {
    goFoo: function() {
        this.theComponent = 'foo';
    },
    goBar: function() {
        this.theComponent = 'bar';
    },
  }
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <button @click="goFoo">Foo</button>
  <button @click="goBar">Bar</button>
  <component :is="theComponent" v-bind="somethingWeWantToPass"></component>
</div>


<template id="foo">
  <div>
    Foo
  </div>
</template>

<template id="bar">
  <div>
    Bar
    <div>This is a prop:  {{ this.test }}</div>
  </div>
</template>

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

fabricJS: clicking on various buttons with the mouse

I have successfully created multiple canvases on the same page based on the number of PDF pages. However, I am facing an issue where some buttons to add different canvases are not working as expected. What I am attempting to do is add text on mouse down fo ...

Utilizing a Material UI custom theme in React with Typescript: A step-by-step guide

Upon using the tool , I received a js file and a json file following the paths mentioned on the theme generator page: // src/ui/theme/index.js /* src/ui/theme/theme.json */ The files operate smoothly when left with the .js extension. However, when I attem ...

Regex substitute every instance of the phrase CONTAINED within brackets

I am looking to replace all instances of text within brackets, including the brackets themselves, in a given string. The specific text to be replaced will be stored in a variable in Javascript. Using a simple regex in a replace method won't work due t ...

Combining the power of Angular.js and Require.js

As I develop a local app on nw.js using angular.js, I'm starting to question my approach. In my controller, I often find myself writing code like this: .controller('UserSettingsCtrl', function($scope, $mdDialog, $translate) { var fs = ...

Utilizing JSON Objects to Populate a Knockout Form

I am looking to populate a form using knockout data-binding from a JSON object. I currently have the values hardcoded in my knockout setup, but what I really want to achieve is dynamically populating the form based on a JSON object. Here is a link to my ...

Error in IONIC 3: The code is unable to read the 'nativeElement' property due to an undefined value, resulting in a TypeError

I am currently learning about IONIC 3 and working on an app that utilizes the Google Maps API. However, when I try to launch my app, I encounter the following error message: inicio.html Error: Uncaught (in promise): TypeError: Cannot read property ' ...

Issue encountered with Fabric js: Unable to apply pattern fill to a group of rectangles

Greetings, I am in need of some assistance with a coding issue. I have a for loop that generates and adds multiple rectangles to a fabric js canvas. To set a texture for each rectangle, I am using the following code snippet. var rect = new fabric.Rect( ...

TypeORM ensures that sensitive information, such as passwords, is never returned from the database when retrieving a user

I developed a REST API using NestJs and TypeORM, focusing on my user entity: @Entity('User') export class User extends BaseEntity { @PrimaryGeneratedColumn() public id: number; @Column({ unique: true }) public username: string; publi ...

Unexpected anomaly with Jquery's after() method

Currently, I am working on the following task: I want to dynamically add a new student to a table of existing students using AJAX when a student is added through my user interface. The process involves sending the UI input fields to the controller, which ...

Get access to vue-json-excel by downloading it once you have finished the request

Currently, I'm utilizing a library called vue-json-excel, which assists in downloading data from a JSON format. Within the Vue view, my structure looks like this: <div class="column is-narrow" @click="btDispatch"> <json-excel clas ...

Node.js and the Eternal Duo: Forever and Forever-Montior

Currently, I am utilizing forever-monitor to launch a basic HTTP Node Server. However, upon executing the JavaScript code that triggers the forever-monitor scripts, they do not run in the background. As a result, when I end the TTY session, the HTTP server ...

How to change the state using an object as an argument in the useState hook within a function

This code uses a function component: export default function Account() { We define a constant with inputs as objects: const [state, setState] = useState({ profile: true, orders: false, returns: false, coupon: false, referrals: false, rewards: ...

Issue with data entry: unable to enter the letter 'S' in search field

This bug has been a real challenge for me. It's strange, but I'm unable to type the letter "S" into the search input field. Oddly enough, the keyboard seems to be functioning properly. Please find the sandbox below for reference: https://codes ...

A guide on making Rest Requests with VueJs 2 and Symfony 3

Trying to send a PATCH request for an event using VueJs 2, here is the code snippet: // Link and body are defined correctly this.$http.patch(linkUrl, this.baseTerms, {someKey:'any value'}).then(response => { console.log(response.body) ...

Create an array of various tags using the ngRepeat directive to iterate through a loop

I'm familiar with both ngRepeat and forEach, but what I really need is a combination of the two. Let me explain: In my $scope, I have a list of columns. I can display them using: <th ng-repeat="col in columns">{{ col.label }}</th> This ...

Transform JSON into a JavaScript array object using node.js

My knowledge of Javascript is limited and I need assistance with a .json file that has the following structure: { "results": [ { "challenger": { "__type": "Pointer", "className": "Player", "objectId": "STWAxAHKay" }, "c ...

Neglecting the Outcome of Async/Await

I am facing an issue where I need to send different SMS messages to different recipients synchronously, but my current implementation using async/await is not producing the expected results. Below is the code snippet causing the problem: Upon querying fo ...

concealed highcharts data labels

I attempted to create a bar chart using Highcharts, and initially it worked fine. However, I encountered an issue when displaying multiple indicators - the datalabels for certain data points are hidden. For example, the datalabel for "provinsi aceh" is not ...

Dynamic and operational icons accompany the AngularJS search input field

Currently, I am delving into the world of AngularJS and experimenting with a search box. Within this search box, I want to incorporate three icons: a magnifying glass, a cross, and a spinner. For the first scenario, I envision the magnifying glass appearin ...

Updating the Document Object Model

React re-renders only when there is a change in state. However, it may seem like the changes made directly to the real DOM reflect instantly. This might raise questions as to what triggers the re-render when the state remains unchanged. import React from ...