我必须在计算中使用 v-model,否则计算不会 return 一个值

I have to use v-model in computed, otherwise computed doesn't return a value

我是 JS/Vue 的新手。我正在尝试进行动态搜索输入。我正在过滤输入更改,过滤的是从我的 API 中获取的对象数组。奇怪的是,计算方法不会 return 任何数据,除非我在 return 之前使用 this.term,它可以是 console.log() 或任何其他与我的 [=14] =].我错过了什么?

var stops = new Array();
  document.addEventListener("DOMContentLoaded", () => {
    fetch('http://localhost:8080/api/stops/')
      .then(response => response.json())
      .then((data) => {
        window.data = data;

        Object.keys(window.data).forEach(k => {
          stops.push(window.data[k]);
        });
      })
      .catch(err => {
        console.log(err);
      });

  });


  Vue.component('sidebar', {
delimiters: ['{(', ')}'],
data: () => {
  return {
    term: '',
  }
},
computed: {
  filtered() {

    <!--followng line needs to be here for the func to return data-- >
    this.term = this.term 

    return stops.filter(p => p.nameno.toLowerCase().includes(this.term.toLowerCase()));
  }

},
template:

  `
    <div id="sidebarContain" >
        <input id="sidebar-search" type="text" v-model="term" >

        <div v-for="tram in filtered" :key="tram.name">
            <span >{(tram.nameno)}</span>
            <span ></span>
        </div>
    </div>
`,
methods: {
},
});

这是因为 stops 不在您的 Vue 数据对象中,所以它无法对更改做出反应。将加载逻辑移到mounted方法中,在data对象中添加一个stops属性,在mounted方法中使用this.stops = ...设置:


Vue.component('sidebar', {
  delimiters: ['{(', ')}'],
  data: () => {
    return {
      term: '',
      stops: []
    }
  },
  computed: {
    filtered() {
      this.term = this.term 

      return this.stops.filter(p => p.nameno.toLowerCase().includes(this.term.toLowerCase()));
    }
  },
  mounted() {
    fetch('http://localhost:8080/api/stops/')
      .then(response => response.json())
      .then((data) => {
        window.data = data;

        Object.keys(data).forEach(k => {
          this.stops.push(data[k]);
        });
      })
      .catch(err => {
        console.log(err);
      });
  },
  template:
    `
      <div id="sidebarContain" >
          <input id="sidebar-search" type="text" v-model="term" >

          <div v-for="tram in filtered" :key="tram.name">
              <span >{(tram.nameno)}</span>
              <span ></span>
          </div>
      </div>
  `,
  methods: {
  },
});