Vuejs v-model 将模糊绑定到 axios 参数

Vuejs v-model bind on blur to axios param

我正在尝试将输入传递给 axios 参数。 console.log(country_id) returns country_id 正确模糊, axios country_id 参数未填充, 我错过了什么

<div id="app">

        <input v-model="country_id" v-on:blur="addCountryId" />
        <ul>

            <li v-for="uploaded_segment in uploaded_segments"> @{{ uploaded_segment.name }}</li>
        </ul>
</div>

<script>
    new Vue({

    el: '#app',

    data: {

        uploaded_segments: [],
        country_id :''
    },
    methods: {

        addCountryId(){

     country_id= this.country_id;
     console.log(country_id);

}
},
    mounted() {

 axios.get('/get_segments', {
        params: {
            country_id: this.country_id
        }
    }) .then(response => this.uploaded_segments = response.data);

}
});

正如 user7814783 在对您的 OP 的评论中所解释的那样,已安装的钩子在渲染后仅 运行 一次 - 此时,country_id 仍然是空的 (``)。

您可能更想使用监视功能:

watch: {
  country_id(newlValue) {
    axios.get('/get_segments', {
        params: {
            country_id: this.country_id
        }
    }) .then(response => this.uploaded_segments = response.data);
  }
}

因为这会在用户每次更改 1 个字符时触发请求,请考虑使用惰性标志 (v-model.lazy="country_id") 或去抖观察器函数 (https://vuejs.org/v2/guide/migration.html#debounce-search-demo)

编辑:根据评论回答后续问题:

how can I process multiple params that change on the watch function, the idea is to have multiple selects that filter the segments : paste.laravel.io/8NZeq

将功能移动到一个方法中,为您要查看的每条数据添加一个 wathcer,从每个中调用该方法

watch: {
  country_id: 'updateSegments',
  // short for: country_id: function() {  this.updateSegments() }
  brand_id: 'updateSegments',
},
methods: {
  updateSegments() {
        axios.get('/get_segments', {
            params: {
                country_id: this.country_id,
                brand_id: this.brand_id
            }
        }) .then(response => this.uploaded_segments = response.data);
      }
}