作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个从 API 检索的对象,并且 key 名称未知。我们假设它将采用以下格式:
var attributes = {
"Colour": ["red", "black", "purple"],
"Size": ["8.0", "8.5", "9.0", "9.5", "10.0"]}
如何在不知道 key 的情况下直接在 Vue 中访问这些数据?我知道如果我知道键,以下内容将会起作用,但我正在寻找一个选项,可以在不知道键名称的情况下引用数组,就像通过键名称(方括号)访问普通的 Javascript 值一样。
<table>
<tr>
<th v-for="(values, name) in attributes"> [[ name ]]</th>
</tr>
<td>
<select">
<option v-for="value in attributes.Colour"> [[ value ]] </option>
</select>
</td>
<td>
<select">
<option v-for="value in attributes.Size"> [[ value ]] </option>
</select>
</td>
</table>
到目前为止我已经尝试过这个(例如 attributes[name]
),这似乎不是正确的 Vue 模板语法:
<table>
<tr>
<th v-for="(values, name) in attributes"> [[ name ]]</th>
</tr>
<td v-for="value in attributes[name]">
<select">
<option> [[ value ]] </option>
</select>
</td>
</table>
最佳答案
你需要做这样的事情。
自从你的attributes
是一个具有动态键的对象,循环遍历该对象以获取键。
然后循环遍历对象 attributes
的每个键获取数组列表。
另外,<td>
标签应包含在 <tr>
内标签
function callMe(){
var vm = new Vue({
el : '#root',
data : {
attributes : {
"Colour": ["red", "black", "purple"],
"Size": ["8.0", "8.5", "9.0", "9.5", "10.0"]}
},
methods: {
}
})
}
callMe();
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.11/dist/vue.js"></script>
<div id='root'>
<table>
<tr>
<th v-for="(item, key, index) in attributes "> {{ key }} </th>
</tr>
<tr>
<td v-for="(item, key, index) in attributes">
<select>
<option v-for="name in item"> {{ name }} </option>
</select>
</td>
</tr>
</table>
</div>
</div>
关于javascript - Vue 模板对象键替代引用,无需使用键名称隐式调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56098455/
我是一名优秀的程序员,十分优秀!