Javascript 从vuejs中的方法设置数据

Javascript 从vuejs中的方法设置数据,javascript,vue.js,Javascript,Vue.js,我试图从一个方法中设置一个数据。我正在使用fetch获取rest数据。但是,当我尝试设置数据时,使用this.item='test'不起作用。所以,当我的this.item在里面时“.then”不起作用。但是什么时候出了“.然后”它工作了。。。但我需要使用rest调用来获取数据 Vue.component('internal_menu', { props: ['list'], data: function () { return { item: '1'

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

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"
})
Vue.component('internal_menu'{
道具:[“列表”],
数据:函数(){
返回{
项目:“1”
}
},
方法:{
测试人员(事件)
{
event.preventDefault();
var有效载荷={
方法:“GET”,
标题:{“Accept”:“application/json;odata=verbose”},
凭据:“相同来源”//或凭据:“包括”
}
常量url=_spPageContextInfo.webAbsoluteUrl+
“/_api/Web/Lists/GetByTitle(“+this.list+”)/Items?
$select=标题、Id、链接、图标和$orderby=标题%20asc”;
获取(url、有效负载)
.然后((resp)=>resp.json())
.then(功能(数据)
{
设项目=数据d.结果;
this.item='teste';//此处不起作用
})
.catch(函数(错误){
log(JSON.stringify(error));
});
this.item='tst123';//这里正在工作
},
},
模板:`
{{list}}-{{item}
试试我
`,
挂载:函数(){
这是getMenuData();
}
})
新Vue({
el:“应用程序”
})
谢谢 埃弗顿

当你这样做时:

.then(function(data) 
      {
          let items = data.d.results;
          this.item = 'teste';// this not working here
      })
闭包对该的引用是匿名函数上下文中的。相反,您需要使用
胖箭头
函数来维护
组件的上下文

.then((data) => {
    let items = data.d.results;
    this.item = 'test';
})

我最初认为这是一个
async/await
问题,但我不知道他在哪里调用
teste()
方法。@RuChernChong在模板中按钮的单击功能中。我解决了我的问题。我创建了一个var self并在进入回调之前获取“this”。