vue.js - 我是否将方法中的数据推送到 vuejs 中的模型中?
问题描述
我是 vuejs 的新手,正在从 rest api 查询数据,但在方法部分。我想知道我是否应该将数据从 Ajax 方法推送到数据模型以便在标记中进行条件渲染?如果是这样,我该如何正确地做到这一点?
new Vue({
el: "#app",
data: {
items: [],
Title: ""
},
created: function() {
this.getCurrentUser();
},
methods: {
getCurrentUser: function() {
var root = 'https://example.com';
var headers = {
accept: "application/json;odata=verbose"
}
var vm = this;
var __REQUESTDIGEST = '';
$.ajax({
url: root + "_api/web/currentuser",
type: 'Get',
headers: headers,
success: function(data) {
vm.Title = data.d.Title;
console.log(vm.Title)
if (vm.Title == "Marks, Wendy" || "Adams, Todd") {
document.getElementById("admin").style.display = "block";
}else
{
document.getElementById("admin").style.display = "none";
}
}
})
},
}
})
`<div id="#app">
<span v-if="vm.Title=='bourg,wallace'">Hello!</span>
</div>`
解决方案
1) 在模板中,您不必以vm.Title
or开头this.Title
。
2)您需要将 span 包装在 id 为“app”的东西中,以便它将数据绑定注入到el: #app
.
您可以尝试以下代码段,然后查看Vue 数据/方法指南以了解 Vue 数据/方法的工作原理:
new Vue({
el: "#app",
data: {
items: [],
Title: ""
},
created: function() {
},
methods: {
getCurrentUser: function() {
let root = 'https://example.com';
let headers = {
accept: "application/json;odata=verbose"
}
let vm = this;
let __REQUESTDIGEST = '';
setTimeout(
function(data) {
vm.Title = 'bourg,wallace'
}
, 1000)
},
}
})
<script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
<div id="app">
<button @click="getCurrentUser">Change User</button>
<span v-if="Title=='bourg,wallace'">Hello!</span>
</div>
推荐阅读
- amazon-web-services - 无法连接到 AWS-RDS MySql 数据库
- php - PHP - 如何读取 json 文件头和其他对象并插入 mysql
- objective-c - NSURLConnection 总是 TRUE
- python - 自动化无根安卓智能手机
- javascript - 使用从 ajax 请求返回的数据更新输入“值”属性...传入 [object, Object]。- Django/Python
- c - atomic operator++ 和 atomic_fetch_add_explicit 的区别
- python - 如何在布尔变量上使用 .trace?
- swift - 如何更快地显示来自 Firebase 的数据?
- r - 如何让R函数返回多个参数值
- python-3.x - 从 PyQt4 迁移到 PyQt5