Utilizing Vue to create multiple components and interact with Vuex state properties

I am currently learning Vue and using it with Vuex (without Webpack). However, I am facing some challenges while implementing a simple example and the documentation is not very clear to me.

  1. One issue I encountered is that I cannot access the Vuex store using the this pointer inside the component's computed property. For example: this.$store.state.nav.title. As a workaround, I had to use the global app variable instead. Also, this.$parent and $root did not work as expected.

  2. Another question I have is regarding initializing multiple Vue components simultaneously. Shouldn't they be automatically mounted when I pass the components property to the Vue constructor object? What is the correct way to initialize header, footer, and body components all at once?

var app = new Vue({
    el: document.getElementById('app'),
    data: {
        title: store.state.nav.title
    },
    computed: {},
    methods: {},
    mounted: function(){},
    updated: function(){},
    store: store,
    components: {
        componentheader,
        componentnavbar,
        componentbody,
        componentfooter
    }
});

for (var component_name in app.$root.$options.components) {
    if (typeof app.$root.$options.components[component_name] === 'function') {
        var MyComponent = Vue.extend(app.$root.$options.components[component_name]);
        var component = new MyComponent().$mount();
        document.getElementById('app').appendChild(component.$el);
    }
}

Here is the full example:

// JavaScript code here
// CSS code here
// HTML code here

Answer №1

It appears there is some confusion regarding the difference between Vue Instance and Vue Component. In essence, you only require a single Vue instance with multiple components to build your application.

In response to your first query, the reason it is not functioning is because you did not install the store on each of the Vue instances that you created (you only installed it on one instance named app).

for (var component_name in app.$root.$options.components) {
  if (typeof app.$root.$options.components[component_name] === 'function') {
    var MyComponent = Vue.extend(app.$root.$options.components[component_name]);
    var component = new MyComponent({
      store // <-- install here
    }).$mount();
    document.getElementById('app').appendChild(component.$el);
  }
}

You can see a working example here.

In fact, you can simply make use of store as both store, app.$store, and this.$store refer to the same object. The benefit of using this.$store is that you do not need to import store into every component file when utilizing Single File Components.

To address your second question:

  • You seem to be confused about Global Registration and Local Registration. It is recommended to stick to either global or local registration for a component.

  • When rendering components, you can define your template within <div id="app"> like so:

<div id="app">
  <componentheader></componentheader>
  <componentnavbar></componentnavbar>
  <componentbody></componentbody>
  <componentfooter></componentfooter>
</div>

You can view a working example here.

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 v-model with the input type files in Vue.js allows for easy two

Is there a way to retrieve data from v-model array in an input type of "file" that allows multiple selections? <input type="file" multiple v-model="modFiles[index]"> <input type="file" multiple v-model="modFiles[index]"> <input type="file" ...

The Error Message: "404 Not Found - Your Form Submission Could Not

Greetings, I am currently immersing myself in learning NodeJS and the Express framework. However, I have encountered an issue when attempting to submit a form that is supposed to go to the '/users/register' URL. It appears that my app.js is unabl ...

retrieve the timestamp when a user initiates a keystroke

Seeking assistance from the community as I have been struggling with a problem for days now. Despite searching on Google and Stack Overflow, I haven't found a solution that works for me. My web application features an analog clock, and I need to capt ...

React is having trouble rendering the current weather information

My code is not functioning properly and I am encountering a TypeError that says "cannot read the property of undefined ('temp')". import React, { useEffect, useState } from "react"; import "./css/style.css"; import { BiStreetV ...

What is the most effective way to programmatically recreate scope in AngularJS?

Currently, I am working on implementing UI-router to handle state changes in my application. My initial belief was that switching states on a dynamic route would result in the current scope getting destroyed and a new scope being created for the template w ...

Experiencing difficulties loading Expo Vector Icons in Nextjs

I've spent countless hours trying various methods to accomplish this task, but unfortunately, I have had no luck so far. My goal is to utilize the Solito Nativebase Universal Typescript repository for this purpose: https://github.com/GeekyAnts/nativ ...

Mutation observer fails to observe an element if it is housed within a function

I am attempting to initialize the liveChatAvailable value as true and set the isLoading value to false once the crispClient element loads onto the page. However, when the observer object is placed within a function, the if (crispClient) code does not exec ...

The Chrome extension takes control of the new tab feature by redirecting it to a custom newtab.html

I have a website https://example.com where users can adjust their site preferences, including enabling night mode. To enhance the user experience, I developed a Chrome extension for https://example.com that transforms Chrome's new tab with a custom ne ...

Loop through items in Node.js

Is anyone familiar with a way to obtain the computed styles of anchor tags when hovering over them on a webpage? I've tried using this function, but it only returns the original styles of the anchor and not the hover styles. Any assistance would be gr ...

Dragging elements with jQueryUI multiple times

Is there a way to configure drag and drop functionality so that one element can be dragged multiple times? I attempted to create something similar to this http://jsfiddle.net/28SMv/3/, but after dragging an item from red to blue, the element loses its abi ...

Dynamically allocate a controller to an element following the Bootstrap process

I have a unique AngularJS application that is initialized manually at a specific time. Later on, I need to display an HTML element without any ng-controller assigned to it. Is there a way to dynamically add an ng-controller to this element in order for it ...

tips on customizing buttons within form groups

I have set up two separate form-groups: My goal is to click on each button within each group and toggle its style from grey to green, and vice versa. However, when I click on a button, all buttons within the group turn grey except for the one that was cli ...

What is the best way to create a CSS class for a list element in React?

I am facing an issue with styling buttons in my UI. These buttons represent different domains and are dynamically generated based on data fetched from the server using the componentDidMount() method. Since I do not know the quantity of buttons at the time ...

Error: The document is unable to detect any input values

I've been struggling with this issue for quite some time now and I can't seem to figure it out, no matter how hard I try. It seems that my input field is not capturing the value entered by the user for some unknown reason. Let me share the code ...

Remix is throwing a Hydration Error while trying to process data mapping

While working on my Remix project locally, I encountered a React hydration error. One thing I noticed is that the HTML rendered by the server does not match the HTML generated by the client. This issue seems to be related to the Material UI library usage. ...

The img-wrapper is failing to show the PNG image

I'm having an issue with my code where it displays jpg images but not png. How can I make the img-wrapper show png files as well? In my example, the first image in the array is a jpg while the second is a png. However, I only see the title of the imag ...

Manipulate jQuery to set the table row containing empty table data cells to be lower than the row with

I am using HTML and jQuery to sort my table, including non-standard sorting with multi-tbody. The issue I am facing is that the prices (Цена) in the td are sorted ascending but not correctly. Why is this happening? Additionally, I need to move the tr&a ...

External JavaScript functions remain hidden from the HTML page

Having issues with JavaScript functions. I created functions in a separate file named index.js, but when I use them in index.html like "onclick = function()", the file doesn't recognize the function. <!doctype html> <html lang="{{ app()-> ...

When integrating AngularJS with CKEditor, an error regarding module dependency injection may occur, causing the following message to be displayed:

Just starting out with Angularjs and attempting to integrate Ckeditor into my webapp. Currently encountering the following error: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.5.8/$injector/modulerr?p0=editor&p1=Error%3A%…Flo ...

Retrieve the Checkbox id of a material-ui checkbox by accessing the object

I'm currently working on extracting the id of a Checkbox object in my JSX code. Here's how I've set it up: <div style={{display: 'inline-block', }}><Checkbox id='q1' onclick={toggleField(this)}/></div> ...