如何在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.
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.
There are a couple of small tweaks needed in your HTML to ensure the form components correctly sync with the loaded data:
- Fix the
Act,1961option 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>
- Fix type matching in
v-ifchecks: The API returnsheadvalues 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>
- 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
dataobject (e.g.,v-model="bok.data[0].icted"). If it's unused, you can leave it as-is, but consistency helps maintainability.
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.
- If your API might return
ruleswith multipledataentries, you'll need to adjust your form to usev-foron thedataarray instead of hardcodingdata[0]. - Add validation for required fields to ensure users can't submit incomplete rules.
内容的提问来源于stack exchange,提问作者Wanderer

