Tips for retrieving a reactive variable from a setup() method?

I'm currently working on a small notes app and using Vue3 + Typescript to enhance my skills. The following code snippet demonstrates how to dynamically create and display an Array of notes:

<template>
  <q-layout>
    <div
        v-for="note in allNotes"
        class="note q-ma-sm q-gutter-sm"
        :id="note.id"
    >
      <q-editor
          v-model="note.text"
      >
      </q-editor>
    </div>

    <q-page-sticky position="bottom-right" :offset="[18, 18]">
      <q-btn fab icon="add" color="accent" @click="addNewNote"/>
    </q-page-sticky>
  </q-layout>
</template>

<script lang="ts">
import {defineComponent, ref} from 'vue'

export default defineComponent({
  name: 'App',
  components: {},
  setup() {

    // defining the structure of a single note
    interface Note {
      id: number
      creationDate: string
      text: string
      tags: string[]
      deleted: boolean
      isFocused: boolean
    }

    // storing all the notes in the app
    let allNotes = ref<Note[]>([])

    function addNewNote() {
      const now = new Date()
      allNotes.value.push({
        creationDate: now.toISOString(),
        deleted: false,
        id: now.getTime(),
        tags: [],
        text: "",
        isFocused: false
      })
    }

    function displayedNotes() {
      return allNotes
    }

    return {
      allNotes,
      addNewNote,
    }
  }
});
</script>

<style lang="scss">
</style>

The main concept here is that allNotes contains the notes which are shown using a v-for loop.

I decided to make a minor change by assuming that the displayed notes will be filtered in the future. For this purpose, I introduced a method called displayedNotes which for now simply returns allNotes (filtering functionality will be added later).

<template>
  <q-layout>
    <div
        v-for="note in displayedNotes"
        class="note q-ma-sm q-gutter-sm"
        :id="note.id"
    >
      <q-editor
          v-model="note.text"
      >
      </q-editor>
    </div>

    <q-page-sticky position="bottom-right" :offset="[18, 18]">
      <q-btn fab icon="add" color="accent" @click="addNewNote"/>
    </q-page-sticky>
  </q-layout>
</template>

<script lang="ts">
import {defineComponent, ref} from 'vue'

export default defineComponent({
  name: 'App',
  components: {},
  setup() {

    // defining the structure of a single note
    interface Note {
      id: number
      creationDate: string
      text: string
      tags: string[]
      deleted: boolean
      isFocused: boolean
    }

    // storing all the notes in the app
    let allNotes = ref<Note[]>([])

    function addNewNote() {
      const now = new Date()
      allNotes.value.push({
        creationDate: now.toISOString(),
        deleted: false,
        id: now.getTime(),
        tags: [],
        text: "",
        isFocused: false
      })
    }

    function displayedNotes() {
      return allNotes
    }

    return {
      allNotes,
      displayedNotes,
      addNewNote,
    }
  }
});
</script>

<style lang="scss">
</style>

The changes made include:

  • v-for now loops over displayedNotes instead of allNotes.
  • displayedNotes() has been introduced as a new method.

As a result, no content is displayed, since although displayedNotes is created, it remains empty when allNotes grows.

How can I ensure that displayedNotes remains reactive?

Answer №1

To improve your code structure, consider implementing a computed property in the following way:

const filteredData = computed(() => displayItems())

This approach allows for flexibility in case you decide to rename the displayItems() function and easily incorporate any filtering logic within it. Whenever the allItems data changes, the computed property will update accordingly with the new filteredData.

The next step is to include only filteredData in your return object and use it within your v-for loop instead of allItems.

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 is the best method for executing computations within Vue.js 2?

Here is my second vue component: <template> <div class="row"> <div v-for="item in options"> <div class="panel panel-default panel-product"> .... </div> </div> ...

What is the best way to develop a unique animation for every v-card?

Is there a way to customize each animation so that it is specific to the selected v-card? Right now, when one card is clicked, all of them play the same animation. data: () => ({ show: true, images: [ {url:require('@/assets/london. ...

The value of a checkbox in Ionic 2

I have implemented the code for reading checkbox values in Ionic 2 following the answer provided. However, I encountered an error message in the console: Cannot read property 'indexOf' of undefined Here is my home.html code: <form #leadsF ...

invoke the next function a different privateFunction within rxjs

I'm trying to figure out how to pass the resetPassword data to the _confirmToUnlock method in Typescript/RxJS. Here is my subscribe method: public invokeUnlockModal() { let resetPassword = { userName: this.user?.userName}; //i need to send this ...

Creating object interfaces in TypeScript dynamically based on function parameters

I'm currently working on a small project that involves creating lists of products in a certain format. For example: let products = createList( new Product('product1'), new Product('product2') ) When it comes to accessing a s ...

Building NextJS with Typescript encountered an error while using @auth0/nextjs-auth0

I am currently facing an issue while trying to build my NextJS application using Typescript. The problem lies with the auth0/nextjs-auth0 package, causing persistent errors during installation. One specific error can be found at the following link: https: ...

Ways to retrieve class variables within a callback in Typescript

Here is the code I'm currently working with: import {Page} from 'ionic-angular'; import {BLE} from 'ionic-native'; @Page({ templateUrl: 'build/pages/list/list.html' }) export class ListPage { devices: Array<{nam ...

How can you effectively blend Vue/Angular with other JavaScript resources to enhance your development process?

My curiosity lies in understanding how front-end javascript libraries such as Vue and Angular can seamlessly integrate with other libraries and assets. For instance, if I were to procure a website template already equipped with additional javascript, is it ...

"Exploring the power of index signatures and methods in Typescript

What might be the reason for code producing a ts(2411) error? class Greeter { [key: string]: string | number[]; greeting: string; constructor(message: string) { this.greeting = message; } greet(): string { return "Hel ...

Mastering unit testing with Behaviour Subjects in Angular

I am looking to test the get and set methods of my user.store.ts file. The get() method is used to retrieve users, while addUsers() is utilized to add new Users to the BehaviorSubject. How can I accomplish this? import { Injectable } from '@angular/c ...

Starting up various modules in Angular 6 using arrays

Can an array be declared and used to bootstrap multiple components in module.ts? I attempted the following: export var initialComponents = []; initialComponents.push(AppComponent); if(condition) { initialComponents.push(IchFooterComponen ...

Ensuring type safety in React using TypeScript

Within the code snippet below, I have specified that setLocale should be passed a value of type Locale through LocaleContextValue. However, why does the setLocale function not throw an error if no value is provided as a parameter? Even when I change it t ...

Function in nodejs throwing an error: Return type missing

I am facing an issue with this code snippet while trying to compile the application. public async test(options?: { engine?: Config }): Promise<any> { const hostel = new Service({ list: this.servicesList, createService ...

Automate the process of replacing imports in Jest automatically

Currently, I am in the process of setting up a testbench for a more intricate application. One challenge we are facing is that our app needs to call backend code which must be mocked to ensure the testbench runs efficiently. To address this issue, we utili ...

Editing data in Handsontable may lead to triggering errors in Vuex mutations

I am currently facing an issue with a big data grid that I'm building using Handsontable and Vue. The data is stored in Vuex, but when I try to edit a cell, I encounter mutation errors related to Vuex. In ag-grid, I could use valueSetters and getters ...

efficiently managing errors in a Nest Jest microservice with RabbitMQ

https://i.sstatic.net/sUGm1.png There seems to be an issue with this microservice, If I throw an exception in the users Service, it should be returned back to the gateway and then to the client However, this is not happening! The client only sees the de ...

excessive load on Array parameter

As a fervent Python enthusiast, I have a strong distaste for JavaScript's lack of elegance. Fortunately, I have found a solution to adapt it to my liking. import { createApp } from 'vue' import App from './App.vue' var array_len_ ...

Limit the type to be used for a particular object key in TypeScript

My pet categories consist of 'dog' and 'cat' as defined in the Pet type: type Pet = 'dog' | 'cat' I also have distinct types for allowed names for dogs and cats: type DogName = 'Jack' | 'Fenton&apos ...

What is the best location for storing a props type declaration in a domain-driven design (DDD) project

I am currently integrating Domain-Driven Design (DDD) principles into a Vue project, focusing on applying DDD concepts to the frontend. One question I have is regarding the storage location for a component's props type definition. In Vue, components c ...

When posting on social platforms, the URL fails to display any metadata

We recently completed a project (Web Application) using React .net core with client-side rendering in React. One challenge we encountered was that when the app loads in the browser, it only displays the static HTML initially without the dynamic meta tags. ...