Is it possible to retrieve props in Vue without using methods?

<script lang='ts'>
import GraphWorld from '@/components/GraphWorld.vue'
//  import { defineComponent } from "vue"
export default {
  name: 'GraphView',
  props: ['people', 'prac'],
  components: {
    GraphWorld
  },
  setup() {
    const nodes={}
    const edges={}
    const n= 5
    //  var x = this.prac
    for (let i = 1; i <= n; i++) {
    nodes[`node${i}`] = {
    name: `Node ${i}`
  };
}
    for (let i=1;i<=n-1;i++){
      edges[`edge${i}`]={
        source:`node${i}`,
        target:`node${i+1}`
      }
    }    
    return { nodes, edges }
  },
  methods: {
  }
}

I need assistance with using "prac" in the setup() function. The "prac" variable is a JSON object that I want to iterate through to generate nodes and edges dynamically. I attempted to access this.prac within setup(), but encountered an error. Moving the setup() logic into a method also brought about challenges. Any advice or alternatives would be greatly appreciated.

UPDATE: The revised approach below resolved my issue:

import { reactive, toRefs } from 'vue'
import GraphWorld from '@/components/GraphWorld.vue'
import { defineComponent } from "vue"
export default defineComponent ({
  name: 'GraphView',
  props: ['people', 'prac'],
  components: {
    GraphWorld
  },
  setup(props) {
    const nodes={}
    const edges={}
    const { prac } = toRefs(props)
    const n = reactive( prac.value )
    //  const n= prac.length
    for (let i = 0; i < n.length; i++) {
    nodes[`node${i}`] = {
    name: `${n[i].Organizations}`
  },
  nodes[`node${i+n.length}`] = {
    name: `${n[i].Title}`
  };
}
    for (let i=0;i<n.length;i++){      
      edges[`edge${i}`]={
        source:`node${i}`,
        target:`node${i+n.length}`
      }
    }   
    return { nodes, edges }
  }

Answer №1

To access your props in the setup() function, you can simply use the props argument like this:

<script lang='ts'>
import GraphWorld from '@/components/GraphWorld.vue'

export default {
  name: 'GraphView',
  props: ['people', 'prac'],
  components: {
    GraphWorld
  },
  setup(props) {
    const prac = props.prac
    // Utilize your props here
    return {}
  }
}
</script>

For more information, refer 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

Optimizing Vue / Vuex State Management for Authentication: A Guide

Seeking advice on best practices for using Vuex in a Vue SPA. I have successfully implemented state management for user login status and side-drawer menu using Vuex in my project. However, I am unsure if it is recommended to handle login, logout, and user ...

TypeScript and Express create a powerful array combination capability within the type system

After defining the EventType as either "TYPE A" or "TYPE B", I am looking to create a type for an array that can only contain one or both of these event types. Simply typing it as an EventType[] allows duplicates, which is not ideal. type Test = EventType ...

Tips for altering the color of string outputs

Can you help me modify a function to display different colors based on the output? For instance, I want it to show in orange if the result is too low, and in red if it indicates obesity. bmiCalculation() { var weight = parseInt(this.currentWeight); ...

Screen remains blank as the React webpage fails to load

Hello, I am having issues with my React page not showing up. Can someone please review my code to see if there are any errors? Here is the edited program: index.html <!doctype html> <html lang="en"> <head> <meta charset ...

Creating a sequence of HTTP calls that call upon themselves using RxJs operators

When retrieving data by passing pageIndex (1) and pageSize (500) for each HTTP call, I use the following method: this.demoService.geList(1, 500).subscribe(data => { this.data = data.items; }); If the response contains a property called isMore with ...

Executing a secondary API based on the data received from the initial API call

Currently, I am diving into the world of RxJS. In my project, I am dealing with 2 different APIs where I need to fetch data from the first API and then make a call to the second API based on that data. Originally, I implemented this logic using the subscri ...

Is it possible to integrate BottomNavigation with various components?

Struggling to implement a bottom navigation with TabContent from components. Despite the code below, the tab content does not display and no errors are thrown. PageContainer.vue: <template> <BottomNavigation selectedIndex="1" class="tab__cont ...

Pause for a moment before displaying the VueJS loading screen

When using VueJS, I have implemented a loader to be displayed on each route like this: router.beforeEach((to, from, next) => { store.commit('loading', true); next(); }) However, it seems unnecessary to show the loader for a request that ...

Create a function that takes in a function as an argument and generates a new function that is identical to the original function, except it has one

I want to establish a function called outerFn that takes another function (referred to as innerFn) as a parameter. The innerFn function should expect an object argument with a mandatory user parameter. The main purpose of outerFn is to return a new functio ...

Unexpected behavior: ng2-dragula modelDrop event leading to undefined array

Struggling to figure out the issue with this code. As shown in this GIF, when dragging a div from one container to another, the object disappears and the array becomes undefined. https://i.stack.imgur.com/TELyc.gif Here is the code snippet: Main View.ht ...

Mastering the Art of Broadcasting Routes in Vue 3 SPA with Laravel Sanctum

I'm currently configuring private-channel broadcasting using my vue 3 single page application in conjunction with a laravel sanctum backend. The broadcasting feature works fine when used without any authorization (for non-private channels), but as soo ...

Adjusting characteristics in Angular dynamically through JSON

Having trouble changing the value of [icon]="reactAtom" to use a JSON value? Need assistance in updating the [icon] value based on the 'featureItem' received from the parent component. HTML <div> <fa-icon [icon]="reactAtom" class="i ...

405 (Method Not Allowed) - Incompatibility between Laravel and Vue.Js

Hello everyone, I need some assistance in setting up a notification system that allows users to like the notifications. Currently, I am using Laravel 7 for the backend and Vue.js for the frontend. The code functions properly on my local machine, but once ...

Combining Rollup, Typescript, and converting images to base64 during the loading process

Having trouble preloading an image with Rollup. None of the solutions that should work seem to be effective, and I can't figure out why. Has anyone successfully managed to make this work? Here is my configuration in rollup.config.js: import image fr ...

Using TypeScript to access the outer "this" from a literal getter

When attempting to access the outer "this" scope in Typescript while using getters and setters in object literals, it seems there is no straightforward method. Take for example the code snippet below: class Report { stuff: any[]; options = { ...

The Vue.js component appears to be hidden within the Swal.fire HTML

Here is how I use Swal.Fire in my file1.js: import TextModuleComponent from "../components/TextModuleComponent"; export default { components: {TextModuleComponent} } Swal.fire({ title: 'Sending the offer via email?', ...

The Battle of Extends and Intersection in Typescript

Typescript's concept of extension is akin to C++'s inheritance. Intersection in Typescript involves creating a new object with all the properties from the intersected classes. Why utilize intersection when extends keyword can already merge ...

Ways to keep information hidden from users until they actively search for it

Currently, I have a custom filter search box that is functioning correctly. However, I want to modify it so that the data is hidden from the user until they perform a search. Can you provide any suggestions on how to achieve this? Below is the code I am u ...

Issue with React Context: The type 'Dispatch<SetStateAction<GiftsType>>' cannot be assigned to type '(arr1: string[], arr2: string[]) => void'

I'm currently working on a project in React+TS where I need to create a context that takes two string arrays and updates an object's state with these arrays. I keep encountering a title typo error in the setChoices function inside the return stat ...

React Typescript does not support the use of React-Router

I'm currently working on a React app that utilizes Typescript. The React version is set to "react": "^16.9.0", and the React-Router version is "react-router-dom": "^5.1.2". Within my App.tsx file, the structure looks like this: const App: React.FC ...