ChatGPT解决这个技术问题 Extra ChatGPT

是否有正确的方法在 vuejs 中重置组件的初始数据?

我有一个包含一组特定起始数据的组件:

data: function (){
    return {
        modalBodyDisplay: 'getUserInput', // possible values: 'getUserInput', 'confirmGeocodedValue'
        submitButtonText: 'Lookup', // possible values 'Lookup', 'Yes'
        addressToConfirm: null,
        bestViewedByTheseBounds: null,
        location:{
            name: null,
            address: null,
            position: null
        }
}

这是模式窗口的数据,所以当它显示时,我希望它以这些数据开始。如果用户从窗口中取消,我想将所有数据重置为此。

我知道我可以创建一种方法来重置数据并手动将所有数据属性设置回其原始属性:

reset: function (){
    this.modalBodyDisplay = 'getUserInput';
    this.submitButtonText = 'Lookup';
    this.addressToConfirm = null;
    this.bestViewedByTheseBounds = null;
    this.location = {
        name: null,
        address: null,
        position: null
    };
}

但这似乎真的很草率。这意味着如果我对组件的数据属性进行更改,我需要确保我记得更新重置方法的结构。这并不可怕,因为它是一个小型模块化组件,但它让我大脑的优化部分尖叫。

我认为可行的解决方案是在 ready 方法中获取初始数据属性,然后使用保存的数据来重置组件:

data: function (){
    return {
        modalBodyDisplay: 'getUserInput', 
        submitButtonText: 'Lookup', 
        addressToConfirm: null,
        bestViewedByTheseBounds: null,
        location:{
            name: null,
            address: null,
            position: null
        },
        // new property for holding the initial component configuration
        initialDataConfiguration: null
    }
},
ready: function (){
    // grabbing this here so that we can reset the data when we close the window.
    this.initialDataConfiguration = this.$data;
},
methods:{
    resetWindow: function (){
        // set the data for the component back to the original configuration
        this.$data = this.initialDataConfiguration;
    }
}

但是 initialDataConfiguration 对象随着数据而变化(这是有道理的,因为在 read 方法中,我们的 initialDataConfiguration 正在获取数据函数的范围。

有没有办法在不继承范围的情况下获取初始配置数据?

我是不是想太多了,有更好/更简单的方法吗?

硬编码初始数据是唯一的选择吗?

您是使用 v-show 还是 v-if 来显示模态?
我为css使用引导程序,所以我使用它内置的模式,它利用jquery进行显示和隐藏。所以本质上组件的窗口部分总是在那里,只是隐藏起来。

l
lukas_o

将初始数据提取到组件外部的函数中 使用该函数在组件中设置初始数据 在需要时重新使用该函数来重置状态。

// 组件外:function initialState (){ return { modalBodyDisplay: 'getUserInput', submitButtonText: 'Lookup', addressToConfirm: null, bestViewedByTheseBounds: null, location:{ name: null, address: null, position: null } } } //组件内部: data: function (){ return initialState(); } 方法:{ resetWindow: function (){ Object.assign(this.$data, initialState()); } }


做到了。谢谢!我对答案做了一个小的编辑,但这只是因为 vue 组件需要一个为数据返回的函数,而不仅仅是一个对象。您的答案概念绝对有效并且是正确的,编辑只是为了说明 vuejs 如何处理组件。
您对 data 属性的功能是正确的,那是我马虎。感谢您的编辑。
它现在给出一个错误:[Vue warn]: Avoid replacing instance root $data. Use nested data properties instead.
@SankalpSingha Vue 2.0 不再允许您这样做。您可以改用 Object.assign。这是工作代码:codepen.io/CodinCat/pen/ameraP?editors=1010
对于这个问题 - [Vue 警告]:避免替换实例根 $data。改用嵌套数据属性,试试 this.$data.propName = "new value";
R
Roland

注意,Object.assign(this.$data, this.$options.data()) 不会将上下文绑定到 data()。

所以使用这个:

Object.assign(this.$data, this.$options.data.apply(this))

cc 这个答案最初是 here


即插即用的答案,就像一个魅力。
这个有打字稿安全的版本吗?
g
gertas

要在当前组件实例中重置组件 data,您可以尝试以下操作:

Object.assign(this.$data, this.$options.data())

私下里我有一个抽象的模态组件,它利用插槽来填充对话框的各个部分。当自定义模态包装该抽象模态时,插槽中引用的数据属于 parent component 范围。这是抽象模式的选项,每次显示自定义模式时都会重置数据(ES2015 代码):

watch: {
    show (value) { // this is prop's watch
      if(value) {
        Object.assign(this.$parent.$data, this.$parent.$options.data())
      }
    }
}

当然,您可以微调您的模态实现 - 上面也可以在某些 cancel 钩子中执行。

请记住,不建议从子级更改 $parent 选项,但是我认为如果父组件只是自定义抽象模式而仅此而已,这可能是合理的。


这种技术现在给出了一个 VueJS 警告;见stackoverflow.com/questions/40340561/…
注意,这不会将上下文绑定到 data。因此,如果您在您的 data 方法中使用 this,您可以通过以下方式应用上下文:Object.assign(this.$data, this.$options.data.apply(this))
这些方式与 location.reload() 相比有什么优势?
@Carlos location.reload 完全重新加载网页,这不是我们在尝试重置个人的组件状态时通常需要的。
s
srmico

如果您对警告感到恼火,这是另一种方法:

const initialData = () => ({}) export default { data() { return initialData(); }, 方法: { resetData(){ const data = initialData() Object.keys(data).forEach(k => this[k] = data[k]) } } }

无需弄乱$data。


A
Armin

我必须在子组件内将数据重置为原始状态,这对我有用:

父组件,调用子组件的方法:

<button @click="$refs.childComponent.clearAllData()">Clear All</button >
       
<child-component ref='childComponent></child-component>

子组件:

在外部函数中定义数据,通过定义的函数引用数据对象,定义由父组件调用的 clearallData() 方法

function initialState() {
  return { 
    someDataParameters : '',
    someMoreDataParameters: ''
  }
}

export default {
   data() {
    return initialState();
  },
methods: {
  clearAllData() {
    Object.assign(this.$data, initialState());
},

B
Buksy

重置组件状态的三种方法:

定义关键属性并更改该定义 v-if 属性并将其切换为 false 以从 DOM 卸载组件,然后在 nextTick 之后将其切换回 true 引用将执行重置的组件的内部方法

就个人而言,我认为第一个选项是最清晰的,因为您只能通过 Props 以声明方式控制组件。您可以使用 destroyed 挂钩来检测组件何时卸载并清除您需要的任何内容。

第三种方法的唯一进步是,您可以进行部分状态重置,您的方法仅重置状态的某些部分,但保留其他部分。

下面是一个包含所有选项以及如何使用它们的示例:https://jsbin.com/yutejoreki/edit?html,js,output