Vuejs v-model将模糊绑定到axios param

时间:2017-05-23 10:13:44

标签: laravel vue.js vue-component

我正在尝试将输入传递给axios param。 console.log(country_id)正确返回country_id, axios country_id param未填充, 我错过了什么

<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);

}
});

1 个答案:

答案 0 :(得分:1)

正如用户7814783在对你的OP的评论中解释的那样,挂载的钩子在渲染后只运行一次 - 此时,country_id仍然是空的(``)。

您可能更愿意使用监视功能:

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

由于这会在用户每次更换一个字符时触发请求,请考虑使用惰性标记(v-model.lazy="country_id")或去抖动观察器功能(https://vuejs.org/v2/guide/migration.html#debounce-search-demo

编辑:回复来自公告的后续行动:

  

如何处理在watch函数上更改的多个参数,我们的想法是有多个选择来过滤段: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);
      }
}