我可以从子组件到父组件获取计算数据吗? [英] Can I get computed data from child component to parent component?

查看:27
本文介绍了我可以从子组件到父组件获取计算数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从子组件到父组件获取计算数据?因为我首先将数据从父级发送到子级,然后我想在父组件中使用计算属性(数据).我想这样做是因为我也想在其他组件中重用那个重要的组件(子组件).

我有一个用于过滤我的项目的搜索输入字段,当我写下一些东西时,我想从子组件中取回该列表.

父组件

<input class="form-control form-control-search m-input" autocomplete="off" type="text" v-on:input='testFunc()' v-model="搜索"占位符=搜索..."><分页链接 v-if="items.length > 0" :models="items"><div class="m-list-timeline__item no-timeline" v-for="item in filterItems" v-bind:key="item.id">{{ item.title }}

</paginate-links>

子组件

道具:['item']计算:{过滤项目(){返回过滤器//这里是我的代码}}

那么我可以在父组件中获取filterItems吗?

解决方案

有几种方法可以将数据发送回父级,但我想说的最简单的方法可能是在计算中使用发射.

>

在儿童中:

计算:{我的值(){让 temp = this.num + 1;this.$emit('onNumChange', temp);返回温度;}}

在父模板中:

<my-child-component @onNumChange="changeHandler"/>

在父脚本中

方法:{更改处理程序(值){console.log('值更改为:', value);}}

你可以用 watch 做类似的事情,或者从父级传递一个函数作为通知父级的道具,但我推荐的方法是使用 vuex

https://vuex.vuejs.org/en/

Is there any way to get computed data from child component to parent component? Because I'm sending the data from parent to child first and then I want to use the comuted property (data) in the parent component. I want to do that because I want to reuse that important component (child) in other components too.

I have a search input field for filtering my items, and when i wrote something down i wanna get back that list from the child component.

Parent component

<input class="form-control form-control-search m-input" autocomplete="off" type="text" v-on:input='testFunc()' v-model="search" placeholder="Search...">
<paginate-links v-if="items.length > 0" :models="items">
  <div class="m-list-timeline__item no-timeline" v-for="item in filterItems" v-bind:key="item.id">
    {{ item.title }}
  </div>
</paginate-links>

Child component

props: ['item']
computed: {
    filterItems () {
      return filter // here goes my code
    }
}

So can i get the filterItems in the parent component?

解决方案

There are a couple ways you can send data back to the parent, but probably the easiest way I'd say is using an emit within the computed.

in child:

computed:{
  myVal() {
    let temp = this.num + 1;
    this.$emit('onNumChange', temp);
    return temp;
  }
}

in parent template:

<my-child-component @onNumChange="changeHandler"/>

in parent script

methods: {
  changeHandler(value) {
    console.log('Value changed to: ', value);
  }
}

You could do a similar thing with watch, or pass a function from parent as a prop that notifies the parent, but my recommended way would be to use vuex

https://vuex.vuejs.org/en/

这篇关于我可以从子组件到父组件获取计算数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆