You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue.js中实现rules数组编辑并映射JSON响应数据?

Alright, let's get this Vue.js rule editing feature sorted out for you. I'll walk you through exactly how to map the JSON response data into your existing form, fix any component binding issues, and make sure your rules array stays in the required format after edits.

Step 1: Map JSON Response Data to Your rules Array

First, you need to extract the rules array from your API response and transform it to match your existing data structure (ignoring extra fields like _id). Add a new method to your Vue instance to handle this data mapping:

// Example API response (replace with your actual fetch/axios response)
const apiResponse = {"status":true,"data":[{"_id":"5afd20c8aae8bd215cc3c33e","no":131,"Date":"2000-01-01T00:00:00.000Z","__v":0,"rules":[{"name":"Act,1972","section":"12","_id":"5afd20c8aae8bd215cc3c341","data":[{"head":"no","value":"","_id":"5afd20c8aae8bd215cc3c342"}]},{"name":"Act,1961","section":"42,12","_id":"5afd20c8aae8bd215cc3c33f","data":[{"head":"1","value":"12","_id":"5afd20c8aae8bd215cc3c340"}]}]}]};

addForm = new Vue({
  el: "#addForm",
  data: {
    no:'',
    Date: '',
    rules : [{ name:null, section:null, data : [{head:null,value:null}] }],
  },
  methods: {
    // New method to load rules from API response
    loadRulesFromResponse(response) {
      // Map the API rules to our required structure
      this.rules = response.data[0].rules.map(rule => ({
        name: rule.name,
        section: rule.section,
        data: rule.data.map(item => ({
          head: item.head,
          value: item.value
        }))
      }));
      
      // Fallback to default empty rule if no data exists
      if (!this.rules.length) {
        this.rules = [{ name: null, section: null, data: [{ head: null, value: null }] }];
      }
    },
    addNewRules: function() {
      this.rules.push({ name: null, section: null, data:[{head:null,value:null}] });
    },
  },
  // Call the load method when the component mounts (or after fetching API data)
  mounted() {
    this.loadRulesFromResponse(apiResponse);
  }
});

This method takes the API response, extracts the relevant fields, and assigns the transformed array directly to your rules data property—Vue's two-way binding will automatically update the form with the loaded data.

Step 2: Fix Form Component Binding Issues

There are a couple of small tweaks needed in your HTML to ensure the form components correctly sync with the loaded data:

  1. Fix the Act,1961 option value: Your current option has an extra space in the value (" Act,1961"), which will prevent it from matching the API's "Act,1961" value. Correct it like this:
<select class="form-control" v-model="bok.name">
  <option value="Act,1972">Act,1972</option>
  <option value="Rule,2012">Rule,2012</option>
  <option value="Act,1961">1961</option> <!-- Removed leading space in value -->
</select>
  1. Fix type matching in v-if checks: The API returns head values as strings (e.g., "1"), but your current checks use numeric values. Use strict equality with string values to ensure the conditional sections display correctly:
<!-- Updated to match string value from API -->
<div class="row" v-if="bok.data[0].head === '1'">
  <!-- ... existing content ... -->
</div>

<div class="row" v-if="bok.data[0].head === '4'">
  <!-- ... existing content ... -->
</div>
  1. Optional: Add v-model to the unbound input: The input labeled "icted" doesn't have a v-model—if you need to capture that data, bind it to a field in your data object (e.g., v-model="bok.data[0].icted"). If it's unused, you can leave it as-is, but consistency helps maintainability.
Step 3: Verify Editing & Output Format

Once you've loaded the data and fixed the bindings, editing the form will automatically update your rules array in the exact format you need:

[{name: "Act,1972", section: "12", data: [{head: "no", value: ""}]}, ...]

You can verify this by logging the array to the console (e.g., console.log(this.rules) in a method or dev tools) after making edits—all extra fields from the API will be excluded, and the structure will match your required format.

Step 4: Optional Enhancements
  • If your API might return rules with multiple data entries, you'll need to adjust your form to use v-for on the data array instead of hardcoding data[0].
  • Add validation for required fields to ensure users can't submit incomplete rules.

内容的提问来源于stack exchange,提问作者Wanderer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:36:29