首页 > 解决方案 > 将多对多关系值传递给 vue 文件

问题描述

我有一个与表discounts有多对多关系的items表我为此使用了 Vue.js 和 Laravel

在我的 vue 文件中,我有

data: function() {
     return {
          books:[],
          options:[],
     };
},
methods:{
     getBooks: function(query) {
        axios.post('/admin/search-books',{
            keyword: query,
        }).then((response) => {
           console.log(response.data);
           this.options = response.data;
        }).catch((error) => {
           console.log(error.data);
        })
     },
}

在我的表格中我有这个

<discount-form :action="somthing">
   <form class="form-horizontal form-create" method="post" @submit.prevent="onSubmit" 
       :action="this.action" novalidate>
     <multiselect v-model="books" placeholder="Name / ISBN of Books" label="name" track- 
     by="id" :options="options" :multiple="true" @search-change="getBooks" 
     :show-labels="false" :close-on-select="false" name="books[]">. 
     </multiselect>
   </form>
</discount-form>

我完美地存放了附件,没有任何问题。但是当我进入编辑表单时

我像这样从控制器传递了值

public function edit(Discount $discount) {
    $books = $discount->items
    return view('admin.edit,compact('discount','item'));
}

在我的组件中,我像这样传递了 item 道具

<discount-form :data="{{$discount->toJson()}}" :items="{{ $books->toJson() }}">

和js文件我已经这样做了

props:['items'],
// and added mounted() and done this in that 
mounted() {
    this.items = this.books
}

但这不起作用,并给了我类似这样的错误

 Error in getter for watcher "filteredOptions": "TypeError: Cannot read property 'concat' of undefined"

TypeError: Cannot read property 'concat' of undefined

和别的 ....

标签: phplaravelvue.jsvue-component

解决方案


您应该像这样将对象和数组作为编码 json 传递:

<discount-form :data="@json($discount)" :items="@json($books)">

推荐阅读