从vuejs中的方法设置数据

问题描述 投票:0回答:1

我正在尝试从方法中设置数据。我正在使用fetch来获取休息数据。但是,当我尝试设置数据时,使用this.item ='test'不起作用。所以,当我的this.item在里面时“.then”不起作用。但是什么时候没有“.then”它工作......但我需要使用休息调用来获取数据......

Vue.component('internal_menu', {
   props: ['list'],
   data: function () {
      return {
         item: '1'
      }
   },
methods: {
   teste(event)
   {
       event.preventDefault();
       var payload = {
           method: 'GET',
           headers: { "Accept": "application/json; odata=verbose" },
           credentials: 'same-origin'    // or credentials: 'include'  
       }
       const url = _spPageContextInfo.webAbsoluteUrl + 
       "/_api/Web/Lists/GetByTitle('"+ this.list +"')/Items? 
       $select=Title,Id,Link,Icone&$orderby=Title%20asc";
       fetch(url,payload)
          .then((resp) => resp.json())
          .then(function(data) 
          {
              let items = data.d.results;
              this.item = 'teste';// this not working here
          })
        . catch(function(error) {
             console.log(JSON.stringify(error));
          });
          this.item = 'tst123'; //this working here
     },

 },
 template: `
    <div id='tst'>
       <h3>{{list}} - {{item}}</h3>
        <button v-on:click="teste">Try Me</button>
    </div>
`,
 mounted: function () {
    this.getMenuData();
 }
})

new Vue({
   el: "#app"
})

谢谢埃弗顿

javascript vue.js
1个回答
1
投票

当你这样做:

.then(function(data) 
      {
          let items = data.d.results;
          this.item = 'teste';// this not working here
      })

你的闭包对this的引用是在匿名函数的上下文中。相反,您需要使用fat arrow函数来维护Component的上下文。

.then((data) => {
    let items = data.d.results;
    this.item = 'test';
})
© www.soinside.com 2019 - 2024. All rights reserved.