Laravel 无法从 Vue-multiselect 获取值

Laravel can't get the values from Vue-multiselect

我正在使用 Vue-multiselect 和 Laravel。

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

我无法获取 multiselect 组件的值。我发现了类似的问题,但其中 none 对我有用。

这是我的代码:

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 事件触发它。