Home > Back-end >  Access component parameters inside caller component
Access component parameters inside caller component

Time:05-13

I have a component which I call inside another component as:

COMPONENT 1

<template>
  <FiltersComponent />
</template>


export default Vue.extend({
 components: { FiltersComponent }

)}

So, this FiltersComponents have some parameters I want to access into my component one

COMPONENT 2 DATA

data() {
    return {
      TestList: [] as string[],
      Test2List: null as string[] | null,
    }
  },

How can I access that TestList and Test2List inside COMPONENT 1?

CodePudding user response:

There are multiple possibilities: If one component is a child component or sibling of the other, you might want to take a loop at props (passing data down) and events (passing data up). Otherwise, if they are not siblings or children, you can use a store like vuex.

To use the docs example:

vue entry point: (e.g., app.js):

import { createApp } from 'vue'
import { createStore } from 'vuex'

// Create a new store instance.
const store = createStore({
  state () {
    return {
      someProperty: 'someValue'
    }
  },
  mutations: {
    update (state, value) {
      state.someProperty = value
    }
  }
})

const app = createApp({ /* your root component */ })

// Install the store instance as a plugin
app.use(store)

In your component's script-section:

  this.$store.commit('update', 'YOUR_VALUE')

Other component:

  const val = this.$store.state.someProperty

However, this is only a very basic example. You should definitely check out the docs, especially the sections about state, getters and mutations.

CodePudding user response:

Always store the state as high in the component tree as you need, meaning that if you need these lists inside component 1, store them there. Then, you can use props and events to access and update the data inside component 2.

Alternatively, you can use a centralized store like Vuex.

CodePudding user response:

You can achieve the same using ref,

Check the below example

<template>
  <FiltersComponent ref="childComponent" /> <!-- Adding ref over here -->
</template>


export default Vue.extend({
 components: { FiltersComponent }

)}

then in any of your methods or mounted section in Component 1. You can access Component2 data like

this.$refs.childComponent.TestList

or

this.$refs.childComponent.Test2List

So simple isn't it? ;)

  • Related