我正在学习Vue,不知道我在这里做错了什么。数据从服务器返回(5条记录),但没有被放入<select>
;我得到的只是一个选项{{dept.DName}}
<html>
<head><link href="Content/bootstrap.min.css" rel="stylesheet" />
<meta charset="utf-8" />
<title></title>
</head>
<body class="container">
<div>
<select id="deptList">
<option v-model="selected" v-for="dept in app.depts" v-bind:value="dept.Did">
{{dept.DName}}
</option>
</select>
</div>
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/moment.min.js"></script>
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.3.4"></script>
<script src="Scripts/vue-controller.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
</body>
</html>
Scripts / vue-controller.js包含:
var app = new Vue({
data: {
el: "body",
depts: [],
emps: [],
selected: ""
},
methods: {
getDepts: function () {
console.log("I'm a little teapot"); // this appears in the log
this.$http.get("/Dept/Index").then(function(response) {
this.depts = response.data;
console.log(this.depts); //the expected data does appear in the log
},
function(error) {
console.log(error.statusText);
});
}
},
created: function () {
this.getDepts();
}
})
我是一名C#开发人员,所以我有一半确定我搞砸了这个/那个上下文的东西,但一直无法弄清楚发生了什么。
答案 0 :(得分:3)
有几个问题。
el
不是数据属性,它是Vue定义对象的root属性。body
。事实上,Vue会阻止它。绑定身体内容中的适当元素。v-model
应该在选择中。app.depts
。可以通过模板中的名称引用所有数据属性。
console.clear()
const departments = [
{Did: 1, DName: "Department 1"},
{Did: 2, DName: "Department 2"},
{Did: 3, DName: "Department 3"},
]
var app = new Vue({
el: "#app",
data: {
depts: [],
emps: [],
selected: ""
},
methods: {
getDepts: function () {
console.log("I'm a little teapot"); // this appears in the log
this.$http.post("https://httpbin.org/post", departments).then(function(response) {
this.depts = response.body.json;
},
function(error) {
console.log(error.statusText);
});
}
},
created: function () {
this.getDepts();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue-resource.js"></script>
<div id="app">
<select v-model="selected" id="deptList">
<option v-for="dept in depts" v-bind:value="dept.Did">
{{dept.DName}}
</option>
</select>
<hr>
Selected Department: {{selected}}
</div>
注意:我修改了ajax调用,以便在此环境中工作。假设您正在使用VueResource,那么您的ajax部分代码看起来很好。
答案 1 :(得分:0)
模板中的变量自动限定为“app”,因此您需要删除“app”。从你的模板,所以它将是
<select id="deptList" v-model="selected">
<option v-for="dept in depts" v-bind:value="dept.Did">
{{dept.DName}}
</option>
</select>
答案 2 :(得分:-1)
项目在父选择元素中是已知的!
<select v-model="item.selectedPersonId">
<option v-for="(item, index) in personList" v-bind:value="item.personId">
{{ item.personName }}
</option>
</select>
和js代码是:
var app = new Vue({
el : "#elemName" ,
data : {
personList : [{personName = "Name1" , personId = "1"} ,
{personName = "Name2" , personId = "2"} ] ,
selectedPersonId : 0
}
});
为我工作。感谢Vuejs。