A Vue component nested within another Vue component

Hey there!

Check out this snippet of HTML code:

// index.html
<div data-init="component-one">
  <...>

 <div data-init="component-two">
   <button @click="doSomething($event)">
 </div>
</div>

This part basically involves referencing a Vue instance within another Vue instance. The JavaScript code for this is divided into two files, which are structured like so:

// componentOne.js
new Vue(
  el: '[data-init="component-one"]',
  data: {...},
  methods: {...}
);


// componentTwo.js
new Vue(
  el: '[data-init="component-two"]'
  data: {...}
  methods: {
    doSomething: function(event) {...}
  }
);

The issue I'm encountering here is that the doSomething method from componentTwo isn't being called.

However, when I include some inline content like {{ 3 + 3 }}, it functions as expected. Vue seems to recognize that something exists in that area. Additionally, the @click element disappears upon page load.

I experimented with using inline-template, but it didn't produce the desired outcome in this particular scenario. It seems like it's not suitable for this case, so I abandoned that approach.

What would be the best way to tackle this situation? And how can I ensure everything works smoothly with the current setup?

We're working with Vue version 2.1.8.

Cheers!

Answer №1

When dealing with nested Vue instances, the issue arises when you have two instances nested within each other. It is recommended to either use the same instance or utilize components if elements are nested.

Check out this JSFiddle for reference

// componentTwo.js
var item = Vue.component('item',({
  name:'item',
    template:'<button @click="doSomething($event)">{{ message2 }</button>',
    data: function(){
      return{ 
        message2: 'ddddddddddd!'
    }},
  methods: {
    doSomething: function(event) {alert('s')}
  }
}));

var app = new Vue({
  el: '[data-init="component-one"]',
  data: {
    message: 'Hello Vue!'
  }
});

<div data-init="component-one">
  <button >{{ message }}</button>
  <item></item>
</div>

If separate instances are needed and they must be independent, here's an example:

View another example on JSFiddle

var app = new Vue({
  el: '[data-init="component-one"]',
  data: {
    message: 'Hello Vue!'
  }
});

// componentTwo.js
var ddd = new Vue({
  el: '[data-init="component-two"]',
    data: {
      message: 'ddddddddddd!'
    },
  methods: {
    doSomething: function(event) {alert('s')}
  } 
});

Answer №2

However, when I include some inline elements like {{ 3 + 3 }}, Vue successfully calculates them. This indicates that Vue is recognizing the presence of content.

It's because you have a parent instance named 'componentOne' activating Vue for this specific template. If you need to add another instance within it, you'll have to segregate a portion of the template. Here's an example (note: performance may vary in this snippet!). Alternative

https://jsfiddle.net/qh8a8ebg/2/

// componentOne.js
new Vue({
  el: '[data-init="component-one"]',
  data: {
    text: 'first'
  },
  methods: {}
});


// componentTwo.js
new Vue({
  el: '[data-init="component-two"]',
  data: {
    text: 'second'
  },
  template: `<button @click="doSomething($event)">{{text}}</button>`,
  methods: {
    doSomething: function(event) {
      console.log(event);
    }
  }
});
<script src="https://vuejs.org/js/vue.min.js"></script>
<div data-init="component-one">
{{text}}
</div>
 <div data-init="component-two">
 </div>

Answer №3

In Vue, the button element inside component-two is referred to as a slot. The @click directive value is evaluated in the parent component (component-one). Therefore, the click handler needs to be declared in component-one.

If you want the handler to be specifically handled within component-two, you must declare a click directive for the slot element in its template and pass the handler function accordingly.

Best of luck with your implementation!

Answer №4

While you are on the right track, one thing to note is that you have embedded the second Vue instance within the first one. By simply placing it alongside instead of nesting it, your code will function as intended.

Vue has a mechanism in place to prevent multiple bindings to the same element in order to prevent endless loops. This is precisely why nesting won't work in this case.

Answer №5

Start by using vue-cli to generate a webpack starter app. Run the command: vue init app --webpack

After that, organize your components in the following manner. For more information, visit: https://v2.vuejs.org/v2/guide/components.html#What-are-Components

  1. Begin with main.js

import Vue from 'vue'
import ComponentOne from './ComponentOne.vue'
import ComponentTwo from './ComponentTwo.vue'

new Vue({
  el: '#app',
  template: '<App/>',
  components: { 
    ComponentOne,
    ComponentTwo
  }
})

  1. Next up is ComponentOne.vue

<template>
  <div class="user">
    <div v-for="user in users">
      <p>Username: {{ user.username }}</p>
    </div>
  </div>
</template>


<script>
export default {
  data () {
    return {
      users: [
        {username: 'Bryan'},
        {username: 'Gwen'},
        {username: 'Gabriel'}
      ]
    }
  }
}
</script>

  1. Last but not least, ComponentTwo.vue

<template>
  <div class="two">
    Hello World
  </div>
</template>


<script>
export default {

}
</script>

Answer №6

<div th:if="${msg.replyFloor}">
    <div class="msg-lists-item-left">
        <span class="msg-left-edit"
              th:classappend=" ${msg.unreadCount == 0} ? 'msg-all-read' ">您在</span>
        <span th:text="${msg.topic.title}"
              class="msg-left-edit-res"
              th:classappend=" ${msg.unreadCount == 0} ? 'msg-all-read' ">问题回答</span>
        <span th:text="${msg.type.name}"
              class="msg-left-edit "
              th:classappend=" ${msg.unreadCount == 0} ? 'msg-all-read' ">帖子相关</span>
        <span class="msg-left-edit-number" >
            产生了<span th:text="${msg.unreadCount} ? : ${msg.unreadCount} + '条新' : ${msg.unreadCount} + '条' "
                       th:class="${msg.unreadCount} ? : 'number-inner':''">2132条</span>回复
        </span>
    </div>
    <div class="msg-lists-item-right">
        <span th:text="${msg.lastShowTime}">2017-8-10</span>
    </div>
</div>

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

Looking for assistance with implementing CSS on alternating rows within a table via JavaScript

My JavaScript code dynamically creates rows in an HTML table using a for loop. Below is the for loop that generates rows for my HTML table: for(var j=0;j<5;j++) { var row = createNewRow(obj); jQuery("#test").append(row); } function creat ...

Guide on displaying an enlarged perspective of the area on an ArcGIS Esri Map automatically

In my Angular application, I successfully integrated an ArcGIS Esri map with locations displayed as Pinpoints on the map using a feature layer. Now, I am looking to automatically zoom into a specific location when a user navigates to the map page. How can ...

Running into issues with permissions on AWS Lambda, unable to create a child process

After successfully running my lambda function locally, I encountered some issues when deploying it live. The lambda is designed to convert HTML content from an event source into a PDF using the html-pdf node module, then upload that PDF to an S3 bucket, an ...

"Implementing a dynamic way to assign values to different item types in React

There is an object with multiple values inside: const [sort, setSort] = useState({ "city": [], "price": [], "year": [] }); When the "add" button is clicked, the "city" value should be updated to include certain va ...

Node.js AWS deployment issue: Module not found

I'm in the process of deploying a basic Node.js application on elastic beanstalk. All the necessary dependencies are outlined in my package.json file, and the app is set to listen on port 8081 through an nginx proxy. However, I've encountered an ...

"Utilize Angular to categorize and sort JSON data with drop-down filtering

I have been working on filtering out JSON data using AngularJS. Here is my approach: angular.module('staticSelect', []) .controller('ExampleController', ['$scope', function($scope) { $scope.data = { multipleSelect ...

Improving your scene with multiple cubes using Three.js

I recently came across a raycasting tutorial for threejs on a website, and the author demonstrated adding cubes to the scene in an interesting way: geom = new THREE.CubeGeometry( 5, 5, 5 ); cubes = new THREE.Object3D(); scene.add( cubes ); for(var i = 0 ...

In a designated paragraph, set the display of all <span> elements to none using JavaScript

I have a long paragraph with over 10,000 lines of text and I need a way to quickly remove all the lines without hiding the entire paragraph. Specifically, I want to hide each line individually by changing the span style from "display:block" to "display:non ...

Unable to determine the length of an array in Vue.js due to property being undefined

Within my vue.js data structure, I have the following: data() { return { formData: new Form({ files:[], Count:5, .. } I am attempting to retrieve the length using the following code : <div class="image-input& ...

I am looking to amalgamate a pair of scripts into a single cohesive work

Currently, I am utilizing jQuery toggleClass to switch CSS styles. $ (".test").click(function () { $(this).toggleClass('active'); }); Whenever I click outside of the Bootstrap menu, the menu gets hidden. In addition to this functio ...

Can the console logs be disabled in "Fast Refresh" in NextJS?

When I'm running multiple tests, my browser's console gets cluttered with messages every time a file is saved. Is there a way to disable this feature? For example: [Fast Refresh] completed in 93ms hot-dev-client.js?1600:159 [Fast Refresh] rebuil ...

Within an Angular test scenario, execute a static method from a service that triggers an HTTP get request to fetch stored JSON data. This data is then retrieved and returned back to the service

Currently, I am facing a challenge in my Angular test case where I am trying to load JSON data via an HTTP call. The issue arises when a static method is called from a service spec file named "url-service.spec" to another service named "load-json.service. ...

Invoking a C++ dll in the renderer process of a Node.js application with Electron using node ffi

As I work on developing a windows application using electron, my goal is to utilize the ffi-napi to invoke C++ .dll methods. However, I am facing a challenge with the "Passing_Dll.js" file, where the label with id "GenName" is not being updated when clicki ...

What is the best way to implement two separate fonts in a document using the Monaco editor?

I have implemented react-monaco-editor in my project. In the overall CSS, I have defined a font family to be used as Helvetica, Tahoma, Arial, monospace. However, I also need to customize the font for a specific editor instance on the page to be "Fi ...

Tips for connecting a href to a div id using JQuery for a parallax slider

I'm currently working on the jQuery slider known as Sequence Master Parallax. My goal is to incorporate a menu at the top that allows users to navigate to each slide. However, I am encountering difficulties in linking the href to the div id. I am unsu ...

Encountering unexpected values when utilizing UseContext in React

Utilizing useState within my component: context.js: const searchContext = React.createContext(); In this context, I initialized a state variable searchText with an initial value of an empty string. Header.js: import { useState } from "react"; ...

Difficulty in toggling on and off several form elements with JavaScript

Trying to control multiple form elements on an HTML page with JavaScript has presented a challenge for me. In my form, each row contains a checkbox that should enable/disable the elements on that row. The issue I'm facing is that only the first two f ...

What steps can be taken to resolve the error message: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data?

I'm facing an issue while trying to retrieve data for my map using an AJAX call. The error message I receive is: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data. Interestingly, two previous datasets in my applicatio ...

Create a custom overlay for an image that is centered horizontally and does not have a fixed width

I'm working with this HTML setup: <div class="container"> <img class="image" /> <div class="overlay"> <div class="insides">more content here</div> </div> &l ...

Retrieving all buttons from a webpage and removing those with a specific background-image using JavaScript

Hey everyone, I'm still learning about javascript and other web development languages. My current task is to locate all the buttons on a webpage and remove the ones that have a specific background image. I know about using getElementsByTagName but n ...