VueJs pu sh массив только в значениях массива - PullRequest
0 голосов
/ 21 апреля 2020

У меня есть несколько входных данных, которые я буду sh передавать в переменную формы, но в результате получается массив в массив, а это не то, что мне нужно.

Образцы

Все части прокомментированы, так что вы не запутаетесь.

Это то, что у меня сейчас есть:

array:2 [
  "form" => array:10 [
    "name" => "tjuhr"
    "link_id" => 5
    "description" => null
    "position" => "Kabel Duct (tanah)"
    "cable_id_id" => null
    "images" => []
    // this is the way currently my cores are returning but i need it changed.
    "cores" => array:1 [
      0 => array:2 [
        0 => array:2 [
          "old_core_id" => 3
          "new_core_id" => 11
        ]
        1 => array:2 [
          "old_core_id" => 5
          "new_core_id" => 20
        ]
      ]
    ]
    "longitude" => "45"
    "latitude" => "4"
    "cable_id" => 2
  ]
  // this part below is for testing purpose only (it has to be pushed into form.cores)
  "cores" => array:2 [
    0 => array:2 [
      "old_core_id" => 3
      "new_core_id" => 11
    ]
    1 => array:2 [
      "old_core_id" => 5
      "new_core_id" => 20
    ]
  ]
]

Это то, что я Ищу иметь

array:2 [
  "form" => array:10 [
    "name" => "tjuhr"
    "link_id" => 5
    "description" => null
    "position" => "Kabel Duct (tanah)"
    "cable_id_id" => null
    "images" => []
    // this is how i need my selected ids return.
    "cores" => array:4 [
      0 => 3
      1 => 11
      2 => 5
      3 => 20
    ]
    "longitude" => "45"
    "latitude" => "4"
    "cable_id" => 2
  ]
]

код

Template

<el-dialog title="Add New Titik Closure" :visible.sync="dialogFormVisible">
    <el-form ref="form" :model="form" :label-width="formLabelWidth">
        <el-row :gutter="10">
            <el-col :span="12">
                <el-form-item label="Name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
            </el-col>

            <el-col :span="12">
                <el-form-item label="Link">
                    <el-select style="width: 100%;" filterable clearable v-model="form.link_id" placeholder="Select Link">
                        <el-option
                        v-for="link in links"
                        :key="link.id"
                        :label="link.site_name"
                        :value="link.id">
                            <span style="float: left">
                                {{ link.site_name }}
                            </span>
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="10">
            <el-col :span="12">
                <el-form-item label="Position">
                    <el-select v-model="form.position" style="width: 100%;" placeholder="Please select Kable Position">
                        <el-option
                            v-for="position in positions"
                            :key="position.value"
                            :label="position.label"
                            :value="position.value">
                            </el-option>
                    </el-select>
                </el-form-item>
            </el-col>

            <el-col :span="12">
                <el-form-item label="Cable">
                    <el-select style="width: 100%;" filterable clearable v-model="form.cable_id" placeholder="Select Cable">
                        <el-option
                        v-for="cable in cables"
                        :key="cable.id"
                        :label="cable.name"
                        :value="cable.id">
                            <span style="float: left">
                                {{ cable.name }}
                            </span>
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>

            <el-col :span="12">
                <el-form-item label="Longitude">
                    <el-input v-model="form.longitude"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="Latitude">
                    <el-input v-model="form.latitude"></el-input>
                </el-form-item>
            </el-col>
        </el-row>

        <!-- add button for multiple input -->
        <el-row :gutter="10">
            <el-col :size="24">
                <div v-for="(indexx, b) in variationChilds" :key="b">
                    <!-- child's -->
                    <el-col :span="6">
                        <el-form-item label="From Tube">
                            <el-select @change="fromTubeHandleChange" v-model="closureForm.fromTube" style="width: 100%;" placeholder="Please select Kable Position">
                                <el-option
                                    v-for="tube in fromTube"
                                    :key="tube.id"
                                    :label="tube.name"
                                    :value="tube.id">
                                    </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="From Core">
                            <el-select style="width: 100%;" filterable clearable v-model="indexx.old_core_id" placeholder="Select From Core">
                                <el-option
                                v-for="core in fromCors"
                                :key="core.id"
                                :label="core.name"
                                :value="core.id">
                                    <span style="float: left">
                                        {{ core.name }}
                                    </span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item label="To Tube">
                            <el-select @change="toTubeHandleChange" style="width: 100%;" filterable clearable v-model="closureForm.toTube" placeholder="Select Cable">
                                <el-option
                                v-for="tubee in toTube"
                                :key="tubee.id"
                                :label="tubee.name"
                                :value="tubee.id">
                                    <span style="float: left">
                                        {{ tubee.name }}
                                    </span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="To Core">
                            <el-select style="width: 100%;" filterable clearable v-model="indexx.new_core_id" placeholder="Select To Core">
                                <el-option
                                v-for="coree in toCores"
                                :key="coree.id"
                                :label="coree.name"
                                :value="coree.id">
                                    <span style="float: left">
                                        {{ coree.name }}
                                    </span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-button slot="append"  @click="addChild(b)"  type="success" icon="el-icon-plus"></el-button>
                    <el-button slot="append" @click="removeChild(b)" v-show="b || ( !b == variationChilds.lenghth > 1)" type="danger" icon="el-icon-delete"></el-button>
                </div>
            </el-col>
        </el-row>

        <el-row :gutter="10">
            <el-col :span="24">
                <el-form-item label="Description">
                    <el-input
                        autosize
                        type="textarea"
                        :rows="2"
                        placeholder="Please input your description here."
                        v-model="form.description">
                    </el-input>
                </el-form-item>
            </el-col>
        </el-row>

        <el-row :gutter="10">
            <el-col :span="24">
                <el-form-item label="Gallery">
                    <el-col :span="10">
                        <el-upload
                            class="upload-demo"
                            drag
                            action="/api/upload/singleClosure"
                            :on-exceed="handleExceed"
                            :on-remove="handleRemove"
                            :on-preview="handlePictureCardPreview"
                            :on-success="handleGallerySuccess"
                            :before-remove="beforeRemove"
                            :limit="10"
                            v-model="form.images"
                            multiple>
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">Drop file here or <em>click to upload</em></div>
                            <div class="el-upload__tip" slot="tip">jpg/png files. <br> Maximun 10 images.</div>
                        </el-upload>
                    </el-col>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="onSubmit">Confirm</el-button>
    </span>
</el-dialog>

Script

data() {
    return {
        variationChilds: [
            {
                old_core_id: '',
                new_core_id: ''
            }
        ],
        form: {
                name: '',
                link_id: '',
                description: '',
                position: '',
                cable_id_id: '',
                images: [],
                cores: [],
                longitude: '',
                latitude: '',
        },
    }
},
methods: {
    // add core child
    addChild(index){
        this.variationChilds.push({
            old_core_id: '',
            new_core_id: ''
        });
    },
    // remove cores child
    removeChild(index){
        this.variationChilds.splice(index, 1);
    },
    onSubmit(e) {
        e.preventDefault();
        this.form.cores.push(this.variationChilds); // this how i currently push my data into form.cores
        axios.post('/api/admin/closures', {
            form: this.form,
            cores: this.variationChilds // this part below is for testing purpose only (it has to be pushed into form.cores)
        })
        .then(res => {
            this.$notify({
                title: 'Hooray!',
                message: res.data.message,
                offset: 100,
                type: 'message'
            });

            this.dialogFormVisible = false
            this.form = {
                name: '',
                link_id: '',
                description: '',
                cable_id: '',
                position: '',
                longitude: '',
                images: [],
                cores: [],
                latitude: '',
            };

        })
        .catch(error => {
            var errors = error.response.data;
                let errorsHtml = '<ol>';
                $.each(errors.errors,function (k,v) {
                        errorsHtml += '<li>'+ v + '</li>';
                });
                errorsHtml += '</ol>';

            this.$notify.error({
                title: 'Error',
                dangerouslyUseHTMLString: true,
                message: errorsHtml
            });
        })
    },
}

Screenshot

Вот так выглядит моя форма:

one

Вопрос

Как мне сделать pu sh мои данные в form.cores, как я показал во втором примере кода?

Обновление

Я внес некоторые изменения (возможно, не лучшее решение), но это дает мне результат + небольшая проблема :)

Таким образом, я в основном изменил pu sh в своей функции на этот код:

const valObj = this.variationChilds.map(function(elem){
    return elem.old_core_id;
});
const valObj2 = this.variationChilds.map(function(elem){
    return elem.new_core_id;
});
if(valObj.length > 0)
{
    for (let i = 0; i < valObj.length; i++)
    {
        for (let i = 0; i < valObj2.length; i++)
        {
            this.form.cores.push(valObj[i], valObj2[i]);
        }
    }
}

, теперь он дает мне этот результат

two

Проблема в том, что я получаю свои значения дважды (помечается как Extra в scre Enshot).

1 Ответ

1 голос
/ 21 апреля 2020

РЕДАКТИРОВАТЬ: Если вы хотите l oop через элементы в массиве, не возвращая массив того же размера, вы можете использовать метод forEach для определения вашей пользовательской функции. В вашем случае,

this.variationChilds.forEach(el => {
  this.form.cores.push(el.old_core_id);
  this.form.cores.push(el.new_core_id);
})

должно помочь.

Оригинальный ответ: VariationChilds - это массив, и вы помещаете весь массив как один элемент в массив form.cores, вызывая вашу проблему.

this.form.cores.push(this.variationChilds); // [].push([{old_core, new_core},{old_core,new_core}]

Если вы хотите, чтобы в качестве значения для form.cores использовалась копия VarificationChilds, используйте this.form.cores = this.variationChilds.slice(). В качестве альтернативы, используйте оператор распространения, чтобы вынести sh каждый содержащийся отдельно элемент в новый массив this.form.cores.push(...this.variationChilds)

Или, в зависимости от вашего варианта использования, вы можете просто вывести новую сущность прямо в эту область. form.cores вместо дополнительного слоя между ними.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...