![](/img/trans.png)
[英]Dynamically display fetched data in input field using Laravel and Vue Js
[英]Using vue-tags-input with Laravel
我正在嘗試將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"}]
)中正確呈現(?),但標簽沒有出現在生成的 output 中。 我從文檔中收集到我不應該將tags
聲明為prop
,因為它會與data
中的內容沖突。id
和name
屬性應用於生成的標記的最外層元素,而不是底層輸入標簽,因此這些值不是由包含表單提交的,所以它們目前很漂亮,但沒用。 還有一些我不明白的其他元素——我不知道data
中的tag
屬性是什么,也不知道為什么我可能想要@tags-changed
部分。
我發現了這個類似的問題,但這似乎沒有任何方法可以從 Laravel 傳遞數據。 總的來說,我發現 Vue 非常復雜——它可能是適合這項工作的錯誤工具。
嘗試:
<tagsinput :id="'tags'" :name="'tags'" :tags="{{ json_encode($tags) }}"></tagsinput>
過去我在模板中直接將對象傳遞給 Vue 時遇到了一些麻煩,通常我通過在刀片中編碼變量並在 Vue 中解碼它來解決。
如果要填充輸入標簽,則需要從后端獲取它們,例如使用 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.