我的父组件如下:

<template>
    <div ref="modal" class="modal" tabindex="-1" role="dialog">
        <div class="modal-dialog" role="document">
            <div class="modal-content modal-content-data">
                <form id="form-data">
                    ...
                    <location-select .../>
                    ...
                </form>
            </div>
        </div>
    </div>
</template>
<script>
    import LocationSelect from './LocationSelect.vue'
    export default{
        name: 'CartModal',
        components:{
            LocationSelect,
        },
        mounted(){
            $(this.$refs.modal).on('hidden.bs.modal', () => {
                Object.assign(this.$data, this.$options.data())
            })
        }
    }
</script>

如果模态隐藏,它将重置父组件中的数据,并且它可以工作
我想重置子组件中的数据
我试着这样做:
<template>
    <select class="form-control" v-model="selected" ...>
        ...
    </select>
</template>
<script>
    export default{
        name: 'LocationSelect',
        ...
        created() {
            $(this.$parent.$refs.modal).on('hidden.bs.modal', () => {
                Object.assign(this.$data, this.$options.data())
            })
        }
    };
</script>

但它不起作用
子组件不重置数据
我怎样才能解决这个问题?

最佳答案

此代码的主要问题是LocationSelect中的处理程序是在this.$parent.$refs.modal存在之前添加的。在安装组件之前,ref不存在。
解决这个问题的最简单方法是将代码移动到mounted

mounted() {
  $(this.$parent.$refs.modal).on('hidden.bs.modal', () => {
    Object.assign(this.$data, this.$options.data())
  })
}

或者您可以将其保留在created中并使用nextTick
created() {
  this.$nextTick(() => {
    $(this.$parent.$refs.modal).on('hidden.bs.modal', () => {
      Object.assign(this.$data, this.$options.data())
    })
  })
}

处理这个问题的另一种方法是将ref添加到LocationSelect组件,并添加一个可以从父组件调用的清除它的方法。在LocationSelect中添加此方法:
methods:{
  clear(){
    Object.assign(this.$data, this.$options.data())
  }
}

在父模板中添加引用:
<location-select ref="locationSelect" ... />

在你父母的坐骑上:
mounted(){
  $(this.$refs.modal).on('hidden.bs.modal', () => {
    Object.assign(this.$data, this.$options.data())
    this.$refs.locationSelect.clear()
  })
}

但是,使用vue处理此问题的最惯用方法是修改组件以支持v-model,然后在清除父组件时自动清除它。
<template>
    <select class="form-control" v-model="selected" ...>
        ...
    </select>
</template>
<script>
    export default {
        props: ["value"],
        name: 'LocationSelect',
        computed:{
          selected:{
            get(){ return this.value },
            set(v) { this.$emit('input', v) }
          }
        },
    };
</script>

然后在父模板中:
<location-select v-model="someDataValue" ... />

如果这样做了,那么当父对象清除时,子对象也会自动清除。

关于vue.js - 如何在vue.js 2上从父组件重置子组件中的数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46160368/

10-12 13:02