Search code examples
vue.jsvuejs3primevue

The value don't bind in PrimeVue/TreeSelect


I am using the TreeSelect component from Primevue,

my primevue version is "^3.25.0" and vue version is "^3.2.45"

now when I use this component I expect the value of selected object or even the whole object bind in the related data. But I can did it and I don't know where is the my problem.

I call my component very simple just like this

<TreeSelect v-model="testValue" selectionMode="single" :options="testCategories" placeholder="Select value" />

and this is my testData:

testCategories: [
    {
        id: 1,
        label: 'Category 1',
        value: 'category1',
        children: [
            {
                id: 2,
                label: 'Subcategory 1.1',
                value: 'subcategory1.1'
            },
            {
                id: 3,
                label: 'Subcategory 1.2',
                value: 'subcategory1.2'
            }
        ]
    },
    {
        label: 'Category 2',
        value: 'category2',
        id: 4,
        children: [
            {
                id: 5,
                label: 'Subcategory 2.1',
                value: 'subcategory2.1'
            },
            {
                id: 6,
                label: 'Subcategory 2.2',
                value: 'subcategory2.2'
            }
        ]
    }
]

I must to say, the options are shown in tree select.

and, with this method when I want to log value of testValue I get this object {undefined: true}


Solution

  • You are missing the mandatory "key" attribute of TreeNode, this can be easily resolved by renaming your "id" field, which is not necessary, as "key".

    Once working correctly, TreeNode based components will store selected nodes using a key-boolean pair object, such that a node is considered selected if it's key exists and has the value "true".

    for example, if only the node with key "6" is selected, the value of the ref attached to "v-model:selection-keys" would equal {6: true}