我可以从子组件到父组件获取计算数据吗?

编程入门 行业动态 更新时间:2024-10-19 19:41:03
本文介绍了我可以从子组件到父组件获取计算数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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

父组件

<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/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/en/

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

更多推荐

[db:关键词]

本文发布于:2023-04-27 00:55:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1144949.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   数据   从子

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!