在 vuejs 中将选定对象显示为字符串
Posted
技术标签:
【中文标题】在 vuejs 中将选定对象显示为字符串【英文标题】:Displaying a selected object as string in vuejs 【发布时间】:2020-04-26 01:36:56 【问题描述】:下面是我用来实现 select2 的 html 代码
<!DOCTYPE html>
<html>
<head>
<title>department</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" ></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.12/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="ProgramForm">
<div class="form-row">
<div class="form-group col-md-4">
<label for="department">Department<span style="color:red">*</span></label>
<select v-model="department" class="form-control select2" >
<option> </option>
<option v-for="department in departmentData" v-bind:value="department">department.departmentName</option>
</select>
</div>
</div>
<p>Selecteddepartment</p>
</div>
我的脚本部分如下
<script type="text/javascript" >
$(function ()
var programFormVM=new Vue(
el:"#ProgramForm",
data:function()
return
department:,
departmentData:[
"id": 1, "departmentCode": "HR", "departmentName": "Human Resource" ,
"id": 2, "departmentCode": "ENG", "departmentName": "Engineering" ,
"id": 3, "departmentCode": "AE", "departmentName": "Agricultural Economics" ,
"id": 4, "departmentCode": "FS", "departmentName": "Field Station" ,
"id": 5, "departmentCode": "ARC", "departmentName": "Architecture"
]
,
created:function ()
,
methods:
,
);
$('.select2').select2(
placeholder: "Select a department"
).on('change', function(e)
// var data = $(".select2 option:selected").val();
programFormVM.department=$(".select2 option:selected").val();
);
);
</script>
</body>
</html>
我需要将对象显示为字符串。事实上,一个越来越 [object Object]。我试过 .text() 但它只给出部门的名称。在我的情况下,我需要整个对象,但需要像 “id”:5、“departmentCode”:“ARC”、“departmentName”:“Architecture” 这样的字符串。请帮忙。问候。
【问题讨论】:
【参考方案1】:v-bind:value="department.id"
const selectedValue = <value from select>
const selectedDepartment = this.departmentData.find(x => x.id === selectedVal)
【讨论】:
嗨阿纳托利。我应该如何在 ES5 中应用它。感谢回复 你可以使用 babel 来 polyfill find 方法或者只使用 for 循环语句。 对此表示感谢!以上是关于在 vuejs 中将选定对象显示为字符串的主要内容,如果未能解决你的问题,请参考以下文章
将 JSON 反序列化为 C# 对象以在网格中将嵌套数组显示为字符串