Vuejs 更新另一个函数内部的状态

时间:2021-06-22 10:58:42

标签: javascript vue.js

我是 Vue.js 的新手,想知道我们如何在来自另一个文件的另一个函数中更新组件的状态。我有一个简单的表单,它只有一个输入文件元素。

当用户选择文件时,将触发 onChange 处理程序,但我不知道如何更新其他函数中的状态。

代码:

utils.js:

export const handleUpload = function(event, state) {
    console.log('Selected file: ', event.target.files[0]);
    // Update the selected state.
};

组件:

<template>
  <div>
    <input
      type="file"
      accept="image/*"
      name="photo"
      @change="onFileSelection($event)"
    />
  </div>
</template>

<script>
import { handleUpload } from './utils';

export default {
  name: 'Index',
  date() {
    return {
      selected: null
    };
  },
  methods: {
    onFileSelection: handleUpload
  }
};
</script>

1 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点。

保持 handleUpload 泛型,让它返回数据

例如,您可以让 handleUpload 返回一些您的 VueJS 组件将用于进一步处理的内容。这是为了使 handleUpload 保持真正的通用性并且不包含任何特定于组件的逻辑,因为改变状态是特定于组件的事情。

export const handleUpload = function(event) {
    console.log('Selected file: ', event.target.files[0]);
    
    return event.target.files[0];
};

然后在你的 VueJS 组件中:

data() {
    return {
        selected: null
    };
},
methods: {
    onFileSelection: function(event) {
        const file = handleUpload(event);
        // Then you can change your component state here, e.g.
        this.selected = file;
    }
}

将组件传递给函数(不推荐)

这是可能的,但我个人会避免它,因为它使 handleUpload 变得自以为是(即它需要知道要更改哪些特定组件数据,并且这可能因一个组件而异)。

export const handleUpload = function(event, component) {
    console.log('Selected file: ', event.target.files[0]);
    
    component.selected = event.target.files[0];'
};

然后在你的 VueJS 组件中:

data() {
    return {
        selected: null
    };
},
methods: {
    onFileSelection: function(event) {
        handleUpload(event, this);
    }
}