当用户从Vue.js中的JSON对象中选择第一个键时,如何显示其余键值?

问题描述 投票:0回答:1

我有一个简单的API,可返回国家/地区列表,其拨号代码和国家/地区代码。当用户从选择选项中选择国家名称时,我试图显示拨号代码国家代码。稍后,我将为所选国家/地区名称,代码和拨号代码设置状态。关键是我可以直接为其他两个设置状态,但是我还需要向用户显示country_code和Dial_code。我评论的部分无法正常工作,因为它不在v-for范围内。我该如何解决?

这里是HTML:


<div id="app">
<select>
  <option v-for="country in countries">{{country.country_name }}</option>
</select>
<!-- 
<p>
    Dial Code: {{ country.dial_code }}
</p>
<p>    
    Code: {{ country.country_code }}
</p> 
-->
</div>

这是JS(为示例我修剪了API调用响应:]

new Vue({
  el: '#app',
  data: {
    countries:[
       {
        "country_name":"Afghanistan",
        "dial_code": "+93",
        "country_code": "AF"
       },
       {
        "country_name":"Zimbabwe",
        "dial_code": "+263",
        "country_code": "ZW"
       }
    ]
},
  methods: {
 }
});

所需结果:

enter image description here

预先感谢!

javascript arrays json vue.js
1个回答
0
投票

为选定国家/地区定义属性:

 data: {
    countries:[
       {
        "country_name":"Afghanistan",
        "dial_code": "+93",
        "country_code": "AF"
       },
       {
        "country_name":"Zimbabwe",
        "dial_code": "+263",
        "country_code": "ZW"
       }
    ],selectedCountry:Object

然后在模板中使用v-modelselect绑定到selectedCountry

<select v-model="selectedCountry">
  <option v-for="country in countries">{{country.country_name }}</option>
</select>

然后您可以使用selectedCountry渲染结果,如下所示:

<p>
    Dial Code: {{ selectedCountry.dial_code }}
</p>
<p>    
    Code: {{ selectedCountry.country_code }}
</p> 
© www.soinside.com 2019 - 2024. All rights reserved.