Access data from another Component

谁说我不能喝 提交于 2021-02-11 08:27:49

问题


now i have 2 Components 1 - is just a drop down list v-select

<v-row align="center" >
  <v-col class="d-flex" cols="12" sm="6" v-if="Compounds" >

  <v-select :items="Compounds" 
          v-model="selectedItems" 
          label="Select"
          item-value="id"
          item-text="name"
          v-on:change="selectedCompound">
</v-select>
{{ selectedItems }}
  </v-col>
</v-row>

with method

     methods: {
          selectedCompound(h2o) {
         console.log(h2o);
         console.log("This is from Selected Compound");
                 },

and i call it in another page

          <div>
       <SelectCompound></SelectCompound>
         </div>

now i want to get the method "selectedCompound" and recall it on this page

so i can access the ID of it to reload the page when the user select another name from the v-select


回答1:


Props are passed down, Events are emited up. If you want to communicate directly between the parent and child, you pass props from parent to child, and the child reacts to the change in value. If you however want the parent to react to changes the child component, you need to emit events.

Here is an example.

Child

methods: {
   selectedCompound(h2o) {
       this.$emit('valChange', h2o)
   },
}

Parent

<div>
    <SelectCompound @valChange="handleChange"></SelectCompound>
</div>
methods: {
   handleChange(h2o) {
       // handle here
       console.log('parent noticed change ' + h2o)
   },
}

You can also use a bus (like Vuex) to have all components communicate to a separate state manager, but it increases the complexity quite a bit compared to simple even emit.




回答2:


I made this jsfiddle for you, using the localStorage as persistence if u need to reload the page, and emitting a event when any option of the select is selected, this event triggered is called change on the select tag, then just you have emit to the parent the value selected. And using the life cycle method created() of Vue to init the value from the persistence.



来源:https://stackoverflow.com/questions/58567257/access-data-from-another-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!