【问题标题】:Using vue-tags-input with Laravel在 Laravel 中使用 vue-tags-input
【发布时间】:2020-11-04 02:36:06
【问题描述】:

我正在尝试将vue-tags-input 与 Laravel 7 一起使用。我可以让它以表单的形式出现在页面上,并且我可以填写值,但我看不到如何预先填充标签加载也不如何获取表单中提交的值。最终我想在一个表单中有多个实例(有多个标签字段),因此需要将它包装为一个可重用的组件。

这是我包装原件的组件(resources/js/components/TagsInput.vue):

<template>
    <div>
        <vue-tags-input v-model="tag" :tags="tags" @tags-changed="newTags => tags = newTags"/>
    </div>
</template>

<script>
import VueTagsInput from '@johmun/vue-tags-input';

export default {
    name: "TagsInput",
    components: {
        VueTagsInput,
    },
    data() {
        return {
            tag: '',
            tags: []
        };
    },
};
</script>

组件从resources/js/app.js添加到Vue实例(它是唯一的组件):

const app = new Vue({
    el: '#app',
    components: {
        "tagsinput": require('./components/TagsInput.vue').default
    }
});

这是我想从刀片模板中使用它的方式:

<tagsinput id="tags" name="tags" :tags="{{ $tags }}"></tagsinput>

有几个问题:

  • 通过{{ $tags }} 传递的数据在tags 属性(例如[{"key":"my tag","value":"My Tag"}])中正确呈现(?),但标签不会出现在结果输出中。我从文档中收集到我应该tags 声明为prop,因为它会与data 中的内容冲突。
  • idname 属性应用于生成标记的最外层元素,而不是底层输入标签,因此这些值不是由包含表单提交的,因此它们目前很漂亮,但没用.

还有一些我不明白的其他元素——我不知道data 中的tag 属性是做什么用的,也不知道为什么我可能想要@tags-changed 部分。

我找到了this similar question,但这似乎没有任何方法可以从 Laravel 传递数据。总的来说,我发现 Vue 非常复杂——可能是它不适合这项工作。

【问题讨论】:

  • 我放弃了,vue 确实是这个工作的错误工具。

标签: php laravel vue.js vue-component


【解决方案1】:

如果要填充输入标签,则需要从后端获取它们,例如使用 Laravel,并且需要在 Vue 组件中调用后端:

 props: ['projectid'],

 beforeMount(){
    this.initProjectTags()
 },


 methods: {
 initProjectTags() {
      const url = '/projecttags/' + this.projectid; //Laravel route

      clearTimeout(this.debounce);

      this.debounce = setTimeout(() => {
        axios.get(url).then(response => {

               this.tags = response.data.projecttags.map( a => { return { text: a.name };} );

        }).catch( (error) => console.log(error) );

      }, 600);
    },
}

鉴于您需要传递输入变量(在我的示例中为 $projectid):

        <div id='app'>

            <tags-input
            :id="'tags'"
            :name="'tags'"
            :tags='{{ json_encode($projecttags) }}'
            :projectid="{{ $project->id }}"
            >
            </tags-input>

        </div>

【讨论】:

    【解决方案2】:

    尝试:

    <tagsinput :id="'tags'" :name="'tags'" :tags="{{ json_encode($tags) }}"></tagsinput>
    

    过去我在模板中直接将对象传递给 Vue 时遇到了一些麻烦,通常我通过在刀片中编码变量并在 vue 中解码来解决。

    【讨论】:

    • 谢谢,但这似乎没有帮助。当我检查它时,数据看起来与没有json_encode 的数据完全相同;它在传递给刀片之前已经编码。 idname 属性中的单引号也没有做任何事情——它们仍然没有传递到底层的 input 元素。你将如何解码 Vue 中的值?
    猜你喜欢
    • 1970-01-01
    • 2020-10-23
    • 2019-11-16
    • 2019-06-19
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多