forms - 使用 Vue js 发布具有多个组件的表单的最佳方法是什么

标签 forms webpack vue.js vue-component

当我在狂欢我的 Vue(最近开始,但到目前为止我真的很喜欢学习这个框架)时,出现了几个问题。其中之一是如何从多个组件发布表单。因此,在我继续前进之前,我想问一下您对这种结构化方式的看法,如果我错了,请指出正确的方向。

到此为止。 我正在使用 ASP.NET CORE 2.1 和 Vue JS 模板(使用 webpack)( https://github.com/MarkPieszak/aspnetcore-Vue-starter )开发一个 SPA 项目,我的项目结构在几个容器中,如下所示: 在我的应用程序根目录中,我注册了几个容器

<template>

  <div id="app" class="container">

    <app-first-container></app-first-container>
    <app-second-container></app-second-container>
    <!--<app-third-container></app-third-container>-->
    <app-calculate-container></app-calculate-container>
    <app-result-container></app-result-container>

  </div>   
</template>

<script>
  // imported templates
  import firstContainer from './first-container'
  import secondContainer from './second-container'
  import calculateContainer from './calculateButton-container'
  //import thirdContainer from './third-container'
  import resultContainer from './result-container'

  export default {
    components: {
      'app-first-container': firstContainer,
      'app-second-container': secondContainer,
     // 'app-third-container': thirdContainer,
      'app-calculate-container': calculateContainer,
      'app-result-container': resultContainer
    }
  } 
</script>

在我的第一个容器中,我有几个下拉菜单和两个输入字段以及我的脚本文件,我在其中从 API 获取数据并使用获取的数据填充下拉列表和输入字段。

是这样的(为了演示输入了一些伪代码)

<template>
  <div>
    <h1>Crops table</h1>

    <p>This component demonstrates fetching data from the server. {{dataMessage}}</p>

    <div class="form-row">

      <div class="form-group col-md-6">
        <label  for="exampleFormControlSelect1" class="col-form-label-sm font-weight-bold">1. Some text</label>
        <select class="form-control" id="exampleFormControlSelect1" v-model="pickedCropType" @change="getCropsByType()">
          <option v-for="(cropType, index) in cropTypes" :key="index" :value="cropType.id" :data-imagesrc="cropType.imgPath">{{ cropType.name }}</option>
        </select>
      </div>

      <div class="form-group col-md-6">
        <label for="exampleFormControlSelect2" class="col-form-label-sm font-weight-bold">2. Some text</label>
        <select class="form-control" id="exampleFormControlSelect2">
          <option v-for="(crop, index) in cropSelectList" :key="index" :value="crop.id">{{ crop.name }}</option>
        </select>
      </div>
    </div>

  </div>
</template>

<script>

  import { mapActions, mapState } from 'vuex'

  export default {
    data() {
      return {
        cropTypes: null,
        cropSelectList: null,
        crops: null,
        pickedCropType: null,

      }
    },

    methods: {
      loadPage: async function () {
        try {
          //Get crop types and create a new array with crop types with an added imgPath property
          var cropTypesFinal = [];
          let responseCropTypes = await this.$http.get(`http://localhost:8006/api/someData`);
          responseCropTypes.data.data.forEach(function (element) {

            cropTypesFinal.push(tmpType);
          });


        } catch (err) {
          window.alert(err)
          console.log(err)
        }
      },
      getCropsByType: async function () {
        //Get crops by crop type
        let responseCrops = await this.$http.get(`http://localhost:8006/api/crop/Type/${this.pickedCropType}`);
        var responseCropsData = responseCrops.data.data;
        this.cropSelectList = responseCropsData;
      }
    },

    async created() {
      this.loadPage()
    }
  }
</script>

在我的第二个容器中,我有不同的下拉菜单和不同的输入字段以及不同的脚本等。

所以,我的问题是:

1.) 我在第一个容器和第二个容器中有必需的数据表单字段我有额外的数据并且我的提交按钮在第三个容器中分开(app-result-container) .那么,这种构建容器的正确且合乎逻辑的方法是否正确?如果不是,您能为我指明正确的方向吗?

2.) 在我正在处理/获取/提交特定容器的某些数据的每个容器中输入脚本标记是否明智?我是否应该将脚本标记放在单独的文件中并保持结构整洁,将 html 与 js 文件分开。

例子: 从“某物”导入{某物}

export default {
  data () {
    return {
      someData: 'Hello'
    }
  },
  methods: {
    consoleLogData: function (event) {
      Console.log(this.someData)
    }
  }
}

3.) 我能否将输入值从一个容器发送到另一个容器(在我的特定情况下,从第一个和第二个容器发送到 app-calculate-container(第三个容器))?

如何提交带有计算导入值的返回结果容器

最佳答案

如果您希望组件相互通信或共享数据,您需要从一个组件发出一个事件到父组件并通过 props 向下传递,或者使用某种状态管理模型,例如 Vuex,您的每个组件都可以在其中收听商店。

看看这个代码沙箱:https://codesandbox.io/s/8144oy7xy2

App.vue

<template>
  <div id="app">
    <child-input @input="updateName" />
    <child-output :value="name" />
  </div>
</template>

<script>
import ChildInput from "@/components/ChildInput.vue";
import ChildOutput from "@/components/ChildOutput.vue";

export default {
  name: "App",
  components: {
    ChildInput,
    ChildOutput
  },
  data() {
    return {
      name: ""
    };
  },
  methods: {
    updateName(e) {
      this.name = e.target.value;
    }
  }
};
</script>

ChildInput.vue

<template>
  <input type="text" @input="changeHandler">
</template>

<script>
export default {
  name: "ChildInput",
  methods: {
    changeHandler(e) {
      this.$emit("input", e);
    }
  }
};
</script>

ChildOutput.vue

<template>
  <p>{{ value }}</p>
</template>

<script>
export default {
  name: "ChildOutput",
  props: {
    value: {
      type: String,
      default: ""
    }
  }
};
</script>

这是怎么回事?

ChildInput 组件是一个文本字段,并且在其中的每个更改中都会触发一个事件(使用 this.$emit() 发出并传递整个事件 向上)。

当它触发时,App 正在监听更改,这会触发更新名称数据属性的方法。

因为 name 是一个响应式数据属性,并且作为 prop 传递给 ChildOutput 组件,屏幕重新呈现并更新为写入的文本。

ChildInputChildOutput 都不知道彼此。父级监听传递给它的事件,然后向下传递新的 prop。

这种工作方式很好而且易于理解,但我强烈建议您查看 Vuex,因为当您超出琐碎的任务时,这种方法会变得困惑和复杂。

关于forms - 使用 Vue js 发布具有多个组件的表单的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51673436/

相关文章:

vue.js - 在 Vue.js 中使用对象作为键会产生什么后果?

php - 健全性检查 - 为什么这个 PHP MySql 插入不起作用?

javascript - 自动生成表单的 AngularJS 表单验证

forms - 使用 golang http 库提交表单

javascript - 使用样式组件会导致 `cannot read withConfig of undefined`

typescript - ` ' $props ' is declared but its value is never read.` 错误发生在 Vue3/TypeScript 项目中,而 '$props' 没有被显式使用

php - 从循环创建的表单中检索多行...卡住了

angular - 失败 : Microsoft. AspNetCore.SpaServices[0]

reactjs - 如何删除 Create React App 中的死代码

javascript - Vue.js 中的条件逻辑