从另一个组件访问数据 [英] Access data from another Component

查看:30
本文介绍了从另一个组件访问数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有 2 个组件1 - 只是一个下拉列表 v-select

<v-col class="d-flex" cols="12" sm="6" v-if="化合物" ><v-select :items="化合物"v-model="selectedItems"标签=选择"项目值=id"项目文本=名称"v-on:change="selectedCompound"></v-select>{{ selectedItems }}</v-col></v-row>

用方法

 方法:{选定的化合物(水){控制台日志(h2o);console.log("这是来自选定的化合物");},

我在另一个页面调用它

 

<选择化合物></选择化合物>

现在我想获取方法selectedCompound"并在此页面上调用它

所以当用户从 v-select 中选择另一个名称时,我可以访问它的 ID 以重新加载页面

解决方案

Props 向下传递,Events 向上发出.如果要在父子之间直接通信,则将 props 从父级传递给子级,子级对值的变化做出反应.如果您但是希望父组件对子组件的更改做出反应,您需要发出事件.

这是一个例子.

孩子

方法:{选定的化合物(水){this.$emit('valChange', h2o)},}

<SelectCompound @valChange="handleChange"></SelectCompound>

方法:{handleChange(h2o) {//处理这里console.log('父母注意到变化' + h2o)},}

您也可以使用总线(如 Vuex)让所有组件与单独的状态管理器进行通信,但与简单的甚至发射相比,它增加了相当多的复杂性.

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

解决方案

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.

这篇关于从另一个组件访问数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆