首页 文章

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

提问于
浏览
1

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

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

父组件

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

子组件

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

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

1 回答

  • 3

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

    在孩子:

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

    在父模板中:

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

    在父脚本中

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

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

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

相关问题