【问题标题】:update parent data from recursive child component从递归子组件更新父数据
【发布时间】:2019-05-18 17:20:55
【问题描述】:

我想用 html 和 vuejs 实现文件树视图,为此我有一个递归组件来实现具有多个根的文件树,如下所示: Root 1 - elemnt 1.1 - elemnt 1.2 - ... Root 2 - element 2.1 - element 2.2 我想保存最近点击的项目,我该怎么做呢?

这是组件的相关代码:

Vue.component('item', {
        template: `
        <li>
            <div @click='toggle(category)'>
                {{category.name}}

            <ul v-show="open" v-if="isFolder">
                <item v-for='category in category.children' :category='category'></item>
            </ul>
        </li>
        `,
        props: {
            category: Object
        },
        data(){
            return {
                open: false
            }
        },
        computed: {
            isFolder: function() {
                return this.category.children && this.category.children.length
            }
        },
        methods: {
            toggle(category){
                if (this.isFolder) {
                    this.open = !this.open
                }
            }
        }
    })

这是 HTML

<ul>
            <item v-for='cat in categories' :category='cat'></item>

        </ul>

【问题讨论】:

  • 查看component basics 这是一本很好的读物,就像大多数 vue 文档一样,并且通过一些很好的设计模式和解决方案来解决这个“问题”;)

标签: vue.js vuejs2 vue-component


【解决方案1】:

您遇到的问题是深度反应性,VueJS 文档提供了很好的解释:Reactiviy in Depth - How Changes Are Tracked

有几种方法可以触发组件的渲染。最明显的是this.$forceUpdate()。然而,它迫使组件重新渲染,我不建议使用它。如果在短时间内触发多次,它可能会变慢。

接下来的两个解决方案只比较了组件而没有其他解决方案。

第一种触发渲染的方式:

<script>
export default {
    data: () => {
        return {
            treeData: []
        }
    },
    methods: {
        updateTree () {
            const treeData = JSON.parse(JSON.stringify(this.treeData))
            this.treeData = []
            this.$nextTick(function () => {
                this.treeData = treeData
            })
        }
    }
}
</script>

或者您可以简单地在父级上使用v-if 并从子级调用this.$emit('updateTree')

<template>
    <child-component @update="updateTree" :treeData="treeData" />
</template>

<script>
import ChildComponent from '../components/ChildComponent'
export default {
    data: () => {
        return {
            showTree: true,
            treeData: []
        }
    },
    components: { 'child-component' : ChildComponent },
    methods: {
        fetchAPIData () {
            // ... ajax
            this.treeData = apiResponse
        },
        updateTree () {
            this.showTree = false
            this.$nextTick(function () => {
                this.showTree = true
            })
        }
    },
    mounted () {
        this.fetchAPIData()
    }
}
</script>

【讨论】:

  • 谢谢你的回答,但这不能解决我的问题,我想要的是在父数据的变量中保存最新点击的元素,如果我使用你的方法,唯一保存的元素是根,但是当点击其他元素时,变量不会改变
  • 对不起,我误解了你的问题,我刚刚更新了我的答案:)。
猜你喜欢
  • 2019-02-17
  • 2017-04-16
  • 1970-01-01
  • 2019-11-16
  • 2020-11-21
  • 1970-01-01
  • 2023-02-20
相关资源
最近更新 更多