我將Vue-Select庫與 Vue3 一起使用。我的目標是讓用戶從選項串列中選擇標簽,并且如果選項串列中不存在標簽,也能夠創建新標簽。
這在子組件中作業正常,但我無法將資料傳遞/發送到父組件。我需要父級中的資料,因為我要打包它以便稍后進行表單處理。
如何成功地將標簽從子組件中獲取到父組件的formData.tags屬性中?
代碼和沙箱鏈接:
components/PostEditorTags.vue:
<template>
<v-select
:create-option="(tag) => ({ label: tag, value: tag })"
v-model="selected"
:options="options"
multiple
taggable
@input="$emit('input', selected)"
placeholder="add a tag"
></v-select>
<br />
child component data:
<pre>{{ selected }}</pre>
</template>
<script setup>
import { ref } from 'vue';
import vSelect from 'vue-select';
import 'vue-select/dist/vue-select.css';
defineEmits(['input']);
const options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' },
{ value: 'three', label: 'Three' },
{ value: 'four', label: 'Four' },
{ value: 'five', label: 'Five' },
{ value: 'six', label: 'Six' },
{ value: 'seven', label: 'Seven' },
{ value: 'eight', label: 'Eight' },
{ value: 'nine', label: 'Nine' },
{ value: 'ten', label: 'Ten' },
];
let selected = ref([]);
</script>
components/Parent.vue:
<template>
<h1>Post Tags</h1>
<PostEditorTags @input="setTagsArr" />
<br />
<br />
parent component data:
<pre>{{ formData.tags }}</pre>
</template>
<script setup>
import PostEditorTags from './PostEditorTags.vue';
const formData = {
// title: '',
// content: '',
tags: null,
};
function setTagsArr(x) {
formData.tags = x;
}
</script>
uj5u.com熱心網友回復:
嘗試使用觀察者而不是事件
components/PostEditorTags.vue:
<template>
<v-select
:create-option="(tag) => ({ label: tag, value: tag })"
v-model="selected"
:options="options"
multiple
taggable
placeholder="add a tag"
></v-select>
<br />
child component data:
<pre>{{ selected }}</pre>
</template>
<script setup>
import { ref, defineEmits, watch } from 'vue';
import vSelect from 'vue-select';
import 'vue-select/dist/vue-select.css';
const options = [{ value: 'one', label: 'One' }, { value: 'two', label: 'Two' }, { value: 'three', label: 'Three' }, { value: 'four', label: 'Four' }, { value: 'five', label: 'Five' }, { value: 'six', label: 'Six' }, { value: 'seven', label: 'Seven' }, { value: 'eight', label: 'Eight' }, { value: 'nine', label: 'Nine' }, { value: 'ten', label: 'Ten' },];
let selected = ref([]);
watch(
() => selected.value,
(newValue, oldValue) => {
act(newValue);
}
);
const emit = defineEmits(['input'])
const act = (val) => emit('input', val);
</script>
讓你的資料反應在components/Parent.vue:
<template>
<h1>Post Tags</h1>
<PostEditorTags @input="setTagsArr" />
<br />
<br />
parent component data:
<pre>{{ formData.tags }}</pre>
</template>
<script setup>
import { reactive } from 'vue'
import PostEditorTags from './PostEditorTags.vue';
const formData = reactive({
// title: '',
// content: '',
tags: null,
});
function setTagsArr(x) {
formData.tags = x;
}
</script>
你的演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/481874.html
標籤:javascript Vue.js Vuejs3 维特 选择
