events and self referencing components vue.js

后端 未结 1 1841
我寻月下人不归
我寻月下人不归 2021-01-27 03:24

I have commenting system which allows 1 level thread. Meaning 1st level comment will look like { ...content, thread: [] } where thread may have more comments in it. I thoug

相关标签:
1条回答
  • 2021-01-27 03:37

    If you only have one level of nesting, you could simply pass the component itself as a slot, like so:

    <Comment v-for="comment in comments" :key="comment.id" v-bind="comment">
      <Comment v-for="thread in comment.thread" :key="thread.id" v-bind="thread" />
    </Comment>
    

    Then you will only have to worry about passing props one level deep, as if you only had a single list of comments. I created an example of this on CodeSandbox here: https://codesandbox.io/embed/vue-template-mq24e.


    If you want to use a recursive approach, you'll just have to pass props and events around; there's no magic solution that steps around this. Update CodeSandbox example: https://codesandbox.io/embed/vue-template-doy66.

    You could avoid explicitly passing the removeitem event listener down by having a removeitem action on your Vuex store that you map to your component.

    My opinion here, is that simpler is better, and you don't need recursion for one level of nesting. Put yourself in the shoes of a future developer and make the code easy to read and reason about; that future developer may even be you when you haven't looked at the codebase in a few weeks.

    0 讨论(0)
提交回复
热议问题