Dark Horse] Add classification parameters 126 episodes-132

Table of contents

1. Add dynamic parameters or static properties

Second, render the modification button

1. Bind an event handler to the edit button

2. Then directly copy the added dialog box to modify

3. Add dialog box display and hide

4, reset the modified form operation

5. Write the verification object of the form

6. Click the button to display the modified dialog box

7. It is necessary to obtain the ID parameter in advance and display it in the dialog box

8. Form pre-verification, when the verification is passed, initiate a request

9. Submit parameters to the server

Third, complete the deletion of parameters

4. Render tag edit

1. Loop in the list data function that gets the parameters, and turn the string into an array

2. Render the label in the page and design a loop

3. Optimize the label, add a close button,

4. Optimize the deletion of empty tags

5. Add a text box, you can also switch to a new label when not typing

6. Optimize the different display of two lines of data text boxes

7. The text box automatically gets the focus

8. Text box switch button display

9. Optimization, judging that if the input is a long space, the emptying is illegal data

10. Submit the content of the text box

11. Deletion of tags 

12. When the selected commodity category is not a three-level category, you need to clear the data in the table below

13. Static attributes are the same as dynamic ones, just paste them directly

14. Submit to warehouse


1. Add dynamic parameters or static properties

Find the API first

The parameter name is the string corresponding to fill in

attr-vals is optional, not selected here

Click the Add OK button, add parameters, first add an event handler to the OK button

addParams

                <el-button type="primary" @click="addParams">确 定</el-button>

 //点击按钮,添加参数
        addParams(){
            this.$refs.addFormRef.validate(async valid =>{
                if(!valid) return
                const {data:res}=await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name:this.addForm.attr_name,
                    attr_sel:this.activeName
                })
                if(res.meta.status!==201){
                    return this.$message.error('添加参数失败')
                }
                 this.$message.success('添加参数成功')
                this.addDialogVisible =false
                this.getParamsData()
            })

        }

 Second, render the modification button

1. Bind an event handler to the edit button

 <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog">编辑</el-button>

2. Then directly copy the added dialog box to modify

     <!-- 修改参数的对话框 -->
       <el-dialog @close="editDialogClosed" :title="'修改' + titleText" :visible.sync="editDialogVisible" width="50%">
            <!-- 表单 -->
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
        </el-dialog>

3. Add the display and hide of the dialog box

 //控制修改对话框的显示与隐藏
            editDialogVisible :false
        }

4, reset the modified form operation

     //重置修改的表单操作
        editDialogClosed(){
            this.$refs.editFormRef.resetFields()
        }

5. Write the verification object of the form

            //修改的表单数据对象
            editForm:{},
            //修改表单的验证规则对象
            editFormRules: {
                attr_name: [
                    { required: true, message: '请输入参数名称', trigger: 'blur' }
                ]
            },

6. Click the button to display the modified dialog box

  //点击按钮,展示修改的对话框
        showEditDialog(){
            this.editDialogVisible = true
        },

At this time, click Edit to pop up the modification dialog box

 7. It is necessary to obtain the ID parameter in advance and display it in the dialog box

 The path contains two parameters, which need to be provided to the server

Add a parameter to the edit button for parameter passing

<el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>

then receive

  //点击按钮,展示修改的对话框
        async showEditDialog(attr_id){
            //查询当前参数的信息categories/:id/attributes/:attrId,前面的id是分类的id,后面的id是当前的传参
            const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,{
                params:{attr_sel:this.activeName}
            })
            if(res.meta.status !==200){
                return this.$message.error('获取参数信息失败')
            }
            this.editForm =res.data
            this.editDialogVisible = true
        },

Now click Edit, and the obtained data will appear in the dialog box

 Now that the acquisition of parameter information has been completed, it needs to be submitted to the background when the point is confirmed

8. Form pre-verification, when the verification is passed, initiate a request

 The id of the category and the id of the current parameter will be included in the request path

9. Submit parameters to the server

     //点击按钮修改参数信息
        editParams(){
            //获取表单的引用
            this.$refs.editFormRef.validate(async valid=>{
                if(!valid) return
                const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
            {    attr_name:this.editForm.attr_name,
                attr_sel:this.activeName}
            )
            if(res.meta.status !==200){
                return this.$message.error('修改参数失败')
            }
            this.$message.success('修改参数成功!')
            this.getParamsData()
            this.editDialogVisible = false
        })
    }

Now you can fully implement the modification operation

Third, complete the deletion of parameters

Bind an event handler to the two delete buttons

pass id,

   //根据id删除对应的参数项
        async removeParams(attr_id) {
            //弹窗询问用户是否删除数据
            const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
            ).catch(err => err)
            //此时用户点确定返回的是一个confirm字符串,如果点取消是返回一个错误,如果解决,加一个catch
            //修改好错误之后,用户点击取消删除之后返回的是一个字符串cancel
            // console.log(confirmResult)
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            // console.log('确认了删除')
            const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)

            if (res.meta.status !== 200) {
                return this.$message.error('删除用户失败')
            }
            this.$message.success('删除用户成功')
            this.getParamsData()

        },

 This will delete successfully

Fourth, render the tag tag

 

 All options under the plate type are separated by spaces,

If you want to render the optional items as labels one by one, you must first separate the strings with spaces, and you will get an array as a result of the separation. If you loop the array, you will get the labels

[Idea] Perform a loop on each item returned by the server, and each loop will get a parameter item, and immediately separate the vals on the parameter item from a string into an array, and then re-assign. In this way, the vals in each parameter item is not a string, but an array. Each item in the array can then be rendered as a label by looping through the unwrapped row.

1. Loop in the list data function that gets the parameters, and turn the string into an array

        async getParamsData() {

//将字符串变成数组
            //将每一项都做一个循环forEach,没循环一次都会拿到一个item,
            //每拿到一个item项,都把item.attr_vals这个项用空格做分隔,并重新赋值
            res.data.forEach(item=>{
                item.attr_vals = item.attr_vals.split(' ')
            })

 2. Render the label on the page and design a loop

  <!-- 展开行 -->
                        <el-table-column type="expand">
                       <template slot-scope="scope">
                        <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i">{
   
   {item}}</el-tag>
                       </template>

The resulting page effect

3. Optimize the label, add a close button,

                        <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable >{ {item}}</el-tag>

4. Optimize the deletion of empty tags

 Newly added categories will have an empty label even if there is no label

Need to give a judgment when separating spaces

                item.attr_vals =item.attr_vals ? item.attr_vals.split(' '):[]

 5. Add a text box, you can also switch to a new label when not typing

Find from element

 <template slot-scope="scope">
                                <!-- 循环渲染Tag标签 -->
                                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable>{
   
   { item }}</el-tag>
                                <!-- 输入的文本框 -->
                                <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue"
                                    ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm"
                                    @blur="handleInputConfirm">
                                </el-input>
                            </template>

Comb the text box in element

 //文本框失去焦点,或者摁下enter都会触发
        handleInputConfirm(){
            console.log('ok')
        },
        //点击按钮,展示文本输入框
        showInput(){
            this.inputVisible = true
        }
   //控制按钮与文本框的切换显示
            inputVisible:false,
            //文本框中输入的内容
            inputValue:''

 6. Optimize the different display of two lines of data text boxes

Each rendered expanded row shares the same boolean value, inputvalue

Provide a separate inputvalue for each row of data, which is bound to the boolean value of its own row of data when looping

  res.data.forEach(item => {
                item.attr_vals =item.attr_vals ? item.attr_vals.split(' '):[]
            //控制按钮与文本框的切换显示
            item.inputVisible=false,
            //文本框中输入的内容
            item.inputValue=''
            })

Then use the inputvalue of this line of data directly when the page is rendered

<el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"

delete the data in

Corresponding modifications are also made in the time processing function of the button

<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
   //点击按钮,展示文本输入框
        showInput(row){
            row.inputVisible = true
        }

This way each text is displayed independently

 7. The text box automatically gets the focus

The function called by clicking the button is pasted from the element, and the three lines are the ones that control the automatic focus

  //点击按钮,展示文本输入框,
        showInput(row) {
            row.inputVisible = true
            //文本框自动获得焦点$nextTick方法:当页面上元素被重新渲染之后,才会指定回调函数中的代码
            this.$nextTick(_ => {
                //通过this.$refs的形式获取到页面上的input输入框对象,调用focus函数
                this.$refs.saveTagInput.$refs.input.focus();
            });
        }

8. Text box switch button display

When the button is clicked, it will switch back to the text box, but now when the text box loses focus, it will not switch to the button

The component that should listen for losing focus of the textbox

@keyup.enter.native="handleInputConfirm"

@blur="handleInputConfirm">

One is the trigger button, and the other is the loss of focus will trigger the same function

pass data

 @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">

accept data and close display textbox

    handleInputConfirm(row) {
            row.inputVisible=false
        },

9. Optimization, judging that if the input is a long space, the emptying is illegal data

Make a judgment before the text box is hidden

trim removes spaces from both ends of the string

  //文本框失去焦点,或者摁下enter都会触发
        handleInputConfirm(row) {
            //trim是清除输入字符串两端的空格,如果输入的是一串空格,则是非法数据
            if(row.inputValue.trim().length===0)
            {
                row.inputValue=''
                row.inputVisible=false
                return
            }
            //如果没有return,则证明输入的内容是合法的,需要做后续处理
        },

10. Submit the content of the text box

But after entering a legal value in the text box, it will be saved in inputValue

You only need to push the value into the attr_vals array, because all labels are created by looping this array

In order to prevent spaces before and after, add a TRIM

After push, this text box needs to be hidden and the content should be cleared

 //如果没有return,则证明输入的内容是合法的,需要做后续处理,把输入的值提交到循环标签的数组中
            row.attr_vals.push(row.inputValue.trim())
            row.inputValue=''
            row.inputVisible=false

But now it is only displayed on the current page number, it is not rendered to the background, and it will disappear when the page is refreshed

Need to submit to the background

After the push is completed, a request needs to be initiated to save the data in the background database

 Note that strings are saved in the background when vals are submitted, here we also need to use spaces to splice the array into a string

//在push完成之后需要发起请求,把数据保存到后台数据库中
            const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
            {
                attr_name:row.attr_name,
                attr_sel:row.attr_sel,
                attr_vals:row.attr_vals.join(' '),
            }
            )
            if (res.meta.status !== 200) {
                return this.$message.error('修改参数项失败')
            }
            this.$message.success('修改参数项成功')
        },

Note that you must use a space link when splicing, otherwise it will be merged into one label after refreshing the page

11. Deletion of tags 

Add a close event to the label

Pass the index and this row of data

<el-tag @close="handleClose(i,scope.row)" v-for="(item, i) in scope.row.attr_vals" :key="i" closable>{ { item }}</el-tag>

        //删除对应标签
        handleClose(i, row) {
            //调用splice进行修改
            row.attr_vals.splice(i, 1)
            //把修改后的保存到数据库中,操作和上面的一致,因此,把上面的保存代码抽出来写成一个函数,直接调用
            this.saveAttrVals(row)
        }

Extract the saved data and write it as a function

    //在push完成之后需要发起请求,把数据保存到后台数据库中
            this.saveAttrVals(row)

        },
        //将对attr_vals的操作,保存到数据库中
        async saveAttrVals(row) {
            //在push完成之后需要发起请求,把数据保存到后台数据库中
            const { data: res } = await
                this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
                    {
                        attr_name: row.attr_name,
                        attr_sel: row.attr_sel,
                        attr_vals: row.attr_vals.join(' '),
                    }
                )
            if (res.meta.status !== 200) {
                return this.$message.error('修改参数项失败')
            }
            this.$message.success('修改参数项成功')
        },

12. When the selected commodity category is not a three-level category, you need to clear the data in the table below

The change event is fired whenever the selection changes

Find the change event handler for the cascade selector

In this function, the function to get the parameter list data will be called

Clear many and only here

 //证明选中的不是三级分类
            if (this.selectedCateKeys.length !== 3) {
                this.selectedCateKeys = []
                this.manyTableData=[]
                this.onlyTableData=[]
                return
            }

13. Static attributes are the same as dynamic ones, just paste them directly

Copy the code of the expanded line directly

14. Submit to warehouse

git branch

git status

git add .

git status

git commit =m "Complete development of classification parameters"

git status

git branch

git merge goods_params

git push

Supongo que te gusta

Origin blog.csdn.net/princess66/article/details/128311741
Recomendado
Clasificación