繁体   English   中英

Laravel 无法从 Vue-multiselect 中获取值

[英]Laravel can't get the values from Vue-multiselect

我在 Laravel 中使用Vue- multiselect。

我在表单中使用多选组件让用户选择多个国家。 该组件工作正常,但是当我提交表单并dd()时,它显示[object Object]

我无法获取多选组件的值。 我发现了类似的问题,但没有一个对我有用。

这是我的代码:

ExampleComponent.vue 文件:

<template slot-scope="{ option }">
<div>

<label class="typo__label">Restricted country</label>
<multiselect
          v-model="internalValue"
          tag-placeholder="Add restricted country"
          placeholder="Search or add a country"
          label="name"
          name="selectedcountries[]"
          :options="options"
          :multiple="true"
          track-by="name"
          :taggable="true"
          @tag="addTag"
          >
</multiselect>

<pre class="language-json"><code>{{ internalValue  }}</code></pre>

</div>
</template>

<script>
 import Multiselect from 'vue-multiselect'

  // register globally
  Vue.component('multiselect', Multiselect)

  export default {

  components: {
  Multiselect
  },
   props: ['value'],
   data () {
   return {
   internalValue: this.value,
   options: [
    { name: 'Hungary' },
    { name: 'USA' },
    { name: 'China' }
     ]
   }
 },
watch: {
internalValue(v){
this.$emit('input', v);
}
},
methods: {
addTag (newTag) {
  const tag = {
    name: newTag,
    code: newTag.substring(0, 2) + Math.floor((Math.random() * 10000000))
  }
  this.options.push(tag)
  this.value.push(tag)
  }
 },

 }
 </script>

这是我的注册表:

<div id="select">
  <example-component v-model="selectedValue"></example-component>
  <input type="hidden" name="countriespost" :value="selectedValue">
 </div>
 
<script>
   const select = new Vue({
      el: '#select',
      data: {
         selectedValue: null
           },
         });
</script>

当我提交表单时, countriespost向我显示了这个: [object Object]而不是实际值。

这是因为您提供了一组对象作为options属性:

options: [
  { name: 'Hungary' },
  { name: 'USA' },
  { name: 'China' }
]

所以input发出的值是一个对象。 尝试将选项更改为以下内容:

options: [ 'Hungary', 'USA', 'China' ]

如果您将一组对象传递给多选组件的:options属性,您应该使用 javascript 提交表单,以便您可以在后端提取对象 ID 或任何您需要的内容,然后将它们发送出去。 添加一个这样的方法:

submit: function() {
  let data = {
    objectIds: _.map(this.selectedOptions, option => option.id), //lodash library used here
    // whatever other data you need
  }
  axios.post('/form-submit-url', data).then(r =>  {
    console.log(r);
  });
}

然后使用提交按钮上的@click.stop事件触发它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM