Issues with rendering Vue 3 component, visible in the elements tree but not displaying on the screen

Recently, I delved into Vue to update one of my components with the new syntax in order to grasp Vue 3 better. However, after the modifications, the component that had been functioning perfectly before now seems to be failing to render properly.

The original component is as follows:

<template>
  <div class="user-profile">
    <div>
      <div class="user-profile__user-panel">
        <h1 class="user-profile__username">@{{ user.username }}</h1>
        <div v-if="user.isAdmin" class="user-profile__admin-badge">Admin</div>
        <div class="user-profile__follower-count">
          <string><b>Followers: </b></string> {{ followers }}
        </div>
      </div>
      <NewTwoot @create-twoot="createNewTwoot" />
    </div>
    <div class="user-profile__twoots-wraper">
      <TwootItem
        v-for="twoot in user.twoots"
        :username="user.username"
        :key="twoot.id"
        :twoot="twoot"
        @favorit="toggleFavorite(id)"
      />
    </div>
  </div>
</template>

<script>
import TwootItem from "./TwootItem.vue";

export default {
  name: "UserProfile",
  components: {
    TwootItem,
  },
  data() {
    return {
      followers: 0,
      user: {
        id: 1,
        username: "GabrielBG",
        firstName: "Gabriel",
        lastName: "Gutierrez",
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dbbcb9bc9ba8b8b2beb5b8beb2a8b8b4b7b7f5b8b4b6">[email protected]</a>",
        isAdmin: true,
        twoots: [
          {
            id: 2,
            content: "This is my second twoot",
          },
          {
            id: 3,
            content: "This is my third twoot",
          },
          {
            id: 1,
            content: "This is my first twoot",
          },
        ],
      },
    };
  },
  watch: {
    followers(newFollowerCount, oldFollowerCount) {
      if (oldFollowerCount > newFollowerCount) {
        console.log("You lost a follower!");
      } else {
        console.log("You gained a follower!");
      }
    },
  },
  computed: {
    fullName() {
      return this.user.firstName + " " + this.user.lastName;
    },
  },
  methods: {
    followUser() {
      this.followers++;
    },
    toggleFavorite(id) {
      console.log("Toggling favorite for twoot with id: " + id);
    },
    createNewTwoot(newTwootContent) {
      this.user.twoots.unshift({
        id: this.user.twoots.length + 1,
        content: newTwootContent,
      });
    },
  },
  mounted() {
    this.followUser();
  },
};
</script>

On the other hand, here is the refactored component that seems to not render correctly:

<template>
  <form class="create-twoot" @submit.prevent="createNewTwoot">
    <lable for="new-twoot"
      ><strong>New Twoot</strong> ({{ newTwootCharCount }}/180)
    </lable>
    <textarea id="new-twoot" rows="5" v-model="state.newTwootContent" />
    <div class="create-twoot-type">
      <lable for="twoot-type">
        <strong>Twoot Type</strong>
      </lable>
      <select id="twoot-type" v-model="state.selectedTwootType">
        <option
          :value="option.value"
          v-for="(option, index) in state.twootTypes"
          :key="index"
        >
          {{ option.name }}
        </option>
      </select>
    </div>
    <button
      type="submit"
      :disabled="
        newTwootContent.length === 0 ||
        newTwootContent.length > 180 ||
        newTwootType == 'draft'
      "
    >
      Twoot
    </button>
  </form>
</template>

<script>
import { reactive, computed } from "vue";
export default {
  name: "NewTwoot",
  setup(_props, ctx) {
    const state = reactive({
      newTwootContent: "",
      selectedTwootType: "instant",
      twootTypes: [
        { value: "draft", name: "Draft" },
        { value: "instant", name: "Instant Twoot" },
      ],
    });

    const newTwootCharCount = computed(() => state.newTwootContent.length);

    function createNewTwoot() {
      ctx.emit("create-twoot", state.newTwootContent);
      state.newTwootContent = "";
    }

    return {
      state,
      newTwootCharCount,
      createNewTwoot,
    };
  },
};
</script>

In the element tree, it appears as

<newtwoot></newtwoot>
, suggesting that it's empty instead of displaying the content as expected.

Answer №1

After carefully reviewing the code, I have identified two key issues:

  1. The problem arises from only importing TwootItem in the parent component and neglecting to import NewTwoot. This results in improper rendering of the component.
  2. Furthermore, it appears that the emit function is not properly defined in the child component. You can refer to my detailed explanation in this answer: vue 3 emit warning " Extraneous non-emits event listeners"

To resolve these issues, make sure to import the missing component by including the following line:

import NewTwoot from "./NewTwoot.vue";
. Additionally, add it to the components section as shown below:

components: {
    NewTwoot,
    TwootItem,
}

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

What steps should I take to address a problem involving a callback function?

I'm currently working on an application that aims to connect users with friends based on specific questions they answer. However, I keep encountering an error message stating "TypeError [ERR_INVALID_CALLBACK]: Callback must be a function" when the cod ...

What is the best way to incorporate async and await into my functions within a Node.js environment?

I attempted to implement asynchronous functionality into my code, however, I encountered some difficulties. What steps should I take next? Below are the functions in question: 1. router.post('/urls', (req, response) => { count = 2; webUrl ...

JavaScript unable to remove cookie from system

I'm currently on an external website and attempting to use JavaScript to remove a cookie. Here's what I tried in the console: function deleteAllCookies() { var cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length ...

Display various messages when submitting a form based on Ajax technology

I have been working on a script that utilizes AJAX to process form submissions. While I can successfully submit the form using AJAX and display a success message, I am looking to customize the messages based on the background data processing of the form. ...

Exploring the depths of npm in the realm of frontend development

Currently, I am delving into the realm of Javascript/Node development through self-teaching. While I grasp the concept of npm handling package installations for my Node application on the server side, I am struggling to comprehend how npm assists me with ...

The continuous firing of the postback event of the Asp.Net Button is

Why does the postback event keep firing for my button? Strangely, when I try to debug with Firebug and set a break point on the function(e) part, the code seems to skip right over it. Even using return false doesn't seem to resolve the issue. <sc ...

The variable $ has not been defined in Jquery framework

<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript" src="deployJava.js"></script> <script type="text/javascr ...

Learn the technique in Vue to separate a string using commas and store the values in an array

As a Ruby enthusiast, I am delving into the world of Vue. In my project, users can input multiple styleCodes separated by commas. I aim to store these styleCodes in an array for flexible length calculations. See my code snippet below: <template> &l ...

Clicking on the v-progress-linear component causes the value to update

Whenever I clicked on my <v-progress-linear>, it would change, and I was looking for a way to prevent that. <v-progress-linear v-model="progress" color="primary" height="20" > Solution: Instead of using ...

The function setCustomValidity() will continue to display even after the form has been successfully filled out

My form is very simple and I am trying to validate it using the required attribute: <form name="form"> <label for="Header">Title</label> <input type="text" class="span5" name="Header" ng-model="Message.header" placeholder="Title" on ...

How can we access state data in a Vuex component once it is mounted?

My goal is to initialize a Quill.js editor instance in a Vue component once it is loaded using the mounted() hook. However, I am facing an issue where I need to set the Quill's content using Quill.setContents() within the same mounted() hook with data ...

AngularJS Setting Default Values in HTML Pages

My goal is to set the default value for a dropdown in an Angular HTML Page. The page uses tabs, and I want the default value to load when a specific tab is clicked. <div class="col-md-9" ng-cloak ng-controller="ServiceTypeController"> <md-conten ...

Rails successfully processed the request with a 200 OK status code, however, the $.ajax() function is triggering the 'error' callback instead of the 'success' callback

In my controller, the ajax request is handled as shown below (simplified): def create ... @answer = Answer.new(video: video_file) if @answer.save render json: @answer.video.url else ... end end This is how I have defined my ajax function: $.aja ...

Managing HTTP requests across different HTML pages in a Cordova mobile application

I have developed a Multiple Page Application (MPA) for Android and iOS which navigates to different pages when users want to view them. Everything is running smoothly so far, but I now want to add some backend sync features. The issue I am facing is that I ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...

Guide on sending JSON data to a server and receiving JSON/XML in response with JSP

I am new to developing web applications. I have successfully created a dynamic web project using Java EE on a Glassfish server. Now, I am trying to enable clients to send data to the server using JSON and receive data from the server in either JSON or XML ...

What is the best method for extracting specific JSON response elements and appending them to an array?

I've been utilizing the Nomics cryptocurrency API in my project. Below is an example of the Axios call: axios.get(apiURL + apiKey + apiSpecs) .then(function (response) { // sort data by highest market cap console.log(response.data) }) Here' ...

Is it necessary to encapsulate Factory calls within a function in my Controller file?

Typically, I call a Factory from my Angular controller directly within the controller function without creating a separate method. For instance: (function () { 'use strict'; angular.module("Dashboard") .controller("DashboardController", D ...

Encountering Timeout Issues with Reading Streams on Amazon S3 using Express.js

I am currently facing an issue with streaming videos from an Amazon S3 Bucket. It seems that everything works perfectly when calling my REST endpoint once, but the problem arises when trying to stream the video simultaneously from multiple browsers. The er ...

Calculation of time intervals based on input values from text boxes, calculating quarters of an hour

I am facing a couple of challenges: -I am trying to calculate the time duration in hours between two military times input by the user in two textboxes. The result should be in quarter-hour intervals like 2.25 hours, 2.75 hours, etc. -The current calculat ...