首页 > 解决方案 > 我是否将方法中的数据推送到 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>`

标签: vue.js

解决方案


1) 在模板中,您不必以vm.Titleor开头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>


推荐阅读