简体   繁体   English

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

[英]Vuejs update the state inside the other function

I'm new to Vue.js and wanted to know how we can update the state of the component inside another function that is coming from another file.我是 Vue.js 的新手,想知道我们如何在来自另一个文件的另一个函数中更新组件的状态。 I have a simple form that only has an input file element.我有一个简单的表单,它只有一个输入文件元素。

When the user will select the file then the onChange handler will trigger but I don't know how to update the state inside other functions.当用户选择文件时,onChange 处理程序将触发,但我不知道如何更新其他函数中的状态。

Code:代码:

utils.js:实用程序.js:

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

Component:成分:

<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>

There are several ways to do it.有几种方法可以做到。

Keep handleUpload generic and simply let it return data保持handleUpload通用并让它返回数据

You can, for example, let handleUpload return something that your VueJS component will use to work on further.例如,您可以让handleUpload返回您的 VueJS 组件将用于进一步处理的内容。 This is so that handleUpload remains truly generic and does not contain any component-specific logic, since mutating a state is something specific to a component.这是为了使handleUpload保持真正的通用性并且不包含任何特定于组件的逻辑,因为改变状态是特定于组件的。

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

Then in your VueJS component:然后在您的 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;
    }
}

Pass component into function (not recommended)将组件传递给函数(不推荐)

This is possible but personally I would avoid it, because it makes handleUpload opiniated (ie it needs to know what specific component data to change, and that may be different from one component to another).这是可能的,但我个人会避免它,因为它使handleUpload独立(即它需要知道要更改哪些特定组件数据,并且可能从一个组件到另一个组件不同)。

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

Then in your VueJS component:然后在您的 VueJS 组件中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM