如何在Vue的v-select组件中传递值

3

我是Vue的新手(版本2.5),在我的项目中,我安装了v-select插件,查看文档时有些地方让我感到困惑。

以下是我的代码:

  <template>
   <div class="wrapper">


             <div class="row">
               <div class="col-sm-6">
                 <div class="form-group">
                   <label for="name">Category</label>
                   <v-select  label="category_desc" options="category"></v-select>
                 </div>
               </div>
          </div>
  <button type="button" variant="primary" class="px-4" @click.prevent="next()">next</button>
       </div>
 </template>     

 <script>
   export default {
     name: 'Addproduct',
    data () {
             return {

                 category:[]


             }
           },
     mounted() {
             this.$http.get('http://localhost:3000/api/categories') .then(function (response) {
                 console.log(response.data);
                this.category=response.data

                 })
                 .catch(function (error) {
                   console.log("error.response");
                 });
         },

方法:{ next(){ // console.log('value of v-selection not option' ) eg id 1 has 'country' so i want id 1 in method next() i.e in console.log } } 现在我的问题是如何将axios响应的成功值传递给v-select选项,第二个问题是我如何获取v-select的选定值,例如:当用户单击下一个按钮时,我如何知道v-select中选择了哪个值

2个回答

3
你需要将选项绑定到类别上,例如使用v-bind:options或简写的:options。我建议您使用一个方法来进行ajax调用,然后在mounted()中调用该方法。此外,您可能想要在select元素上使用v-model,因此我在示例中添加了它。
首先,在您的模板中...
 <v-select  v-model="selectedCategory" label="category_desc" :options="category"></v-select>

然后在你的脚本定义中...
data(){
   return{
     category:[],
     selectedCategory: null,
   }
},
methods:{
    getCategories(){
      this.$http.get('http://localhost:3000/api/categories')
           .then(function (response) {
               this.category=response.data
             }.bind(this))
           .catch(function (error) {
               console.log("error.response");
            });
  }
},
 mounted(){
   this.getCategories(); 
 }

这里有一个可用的 jsfiddle https://jsfiddle.net/skribe/mghbLyva/3/


你的代码运行正常,但如果我添加了Ajax响应,它就停止工作。this.$http.get('http://localhost:3000/api/categories') .then(function (response) { console.log(response.data); // this.category=response.data this.category=[response.data]; }) .catch(function (error) { console.log("error.response"); }); 即没有输出结果。 - undefined
谢谢,这个方法有效。我只是在ajax之外添加了var _this=this,然后在ajax内部使用_this.category=[response.data]。 - undefined
1
如果我表达不清楚,对不起。我建议你使用.bind(this)this绑定到作用域中,这样会更加简洁。请参考我上面的编辑。如果我的回答有帮助,请考虑将其标记为被接受的答案。 - undefined

0
我们是在讨论this select component吗?最简单的用法是在你的v-select上放置一个v-model属性。然后这个变量将自动反映用户选择的值。
如果你需要指定选项,可能会需要,那么你还需要提供一个value属性并监听@change事件。

v-model select add in v-select it throw error select not define can you show me some example in new so i got confusev-model 在 v-select 中添加时,会抛出错误“select未定义”。你能给我展示一些新的例子吗?我有点困惑。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接