Home > Software design >  Is there a way to access props outside methods in Vue?
Is there a way to access props outside methods in Vue?

Time:05-21

<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 want to use "prac" in setup(), basically prac is a json and I want to iterate through it to create the nodes and edges. Is there a way to do that, I tried directly using this.prac inside setup(), but that gave me an error. I also tried moving setup() inside the method but that is causing other problems. Any suggestions are appreciated.

CodePudding user response:

You can access your props within setup() by using 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
    // use your props here
    return {}
  }
}
</script>

see more here

  • Related