简体   繁体   中英

Call v-model from a different component in VueJS

How to call a v-model that is placed in a different component? The search text-field is placed in the App.vue and I need to trigger the :search='search' in the Datatable.vue

App.vue code:

    <v-text-field
    v-model="search"
    class="mx-3"
    label="Suche"
    ></v-text-field>

Datatable.vue code:

<v-data-table
ref='dTable'
:items='products'
:search='search'
class='elevation-1'
>

There is a number of different ways you can share data between your components.

In your case, since you have a the v-text-field bound to your search -data, you can simply pass it along to your Datatable component.

<div id="app">
  <v-text-field v-model="search" ...  />
  <Datatable v-bind:search="search" ... />
</div>

Then you have to "catch" and use it in your Datatable component.


Other ways of sharing data:

Service bus

One of the ways is creating a serviceBus , to emit changes to different parts of your application. Take a look at this blog post .

In your case, you would set up a listener for serviceBus.$on('searchInitiated', (query) => { ... }) in your data table component - and in the search component trigger the search by calling serviceBus.$emit('searchInitiated', this.search) ;

This lets you share component state across different components, independent of hierarchy.


Passing Data to Child Components with Props

Another way of "sharing data", is letting a "high level component" keep track of your state - then pass the data on to child components .

This might get cumbersome, if you have a deeply nested component hierarchy - as you have to pass the prop from component to component.


Sending Messages to Parents with Events

You can also emit values from a child component ( Search ) to the parent ( App ), then pass this data on to your DataTable .

A variation of the "Service bus" example, differing on that there is no "shared bus" - you have to specifically attach the callback to your child component.


Share state via vuex

You can also utilize vuex to share state between your components. Here is a great guide for getting started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM