dav*_*ove 1 javascript vue.js vuejs2
我正在学习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>
Run Code Online (Sandbox Code Playgroud)
脚本/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();
}
})
Run Code Online (Sandbox Code Playgroud)
我是C#开发人员,所以中途确定自己搞砸了this / that上下文内容,但一直无法弄清正在发生什么。
There are several issues.
el is not a data property, it is a root property of the Vue definition object.body. In fact, Vue will prevent it. Bind to an appropriate element in the content of the body.v-model should be on the select.app.depts. All data properties can be referenced by name in the template.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();
}
})Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
注意:我修改了ajax调用,以便它可以在这种环境下工作。假设您使用的是VueResource,则用于ajax部分的代码看起来不错。
| 归档时间: |
|
| 查看次数: |
5637 次 |
| 最近记录: |