2

I am looking in the setup function to render an array of buttons. For simplicity purposes I have provided this example below.

When I use an array and push or assign values as default, then place the array with in the render function I do not see any reactivity on click.

setup(props, {emit, slots}) {
    const base_number = ref(1)

    const base_offset= computed(()=> { return base.value + 2 })
    let buttons = [base_offset.value]

    let pageClick =  (event , pageNumber ) => {
       base_number.value = 3
    }

    return  h("ul",{ class: "pagination", 'onClick' : event => { pageClick(event, 1)}},
               buttons
            )

However when I place the array of components like so in the return , reactivity and value updating works.

   //On click will update  base_offset
    return  h("ul",{ class: "pagination", 'onClick' : event => { pageClick(event, 1)}},
                      [base_offset.value]
             )

}

What am I missing and is it possible to pass in a array of vnodes?

1 Answer 1

5

Instead of returning the VNode array directly from setup(), it should return a render function that returns a VNode array (and you should see a browser console warning regarding this):

export default {
  setup() {
    // return h(...) ❌
    return () => h(...) ✅
  }
}

Within that render function, create the buttons array of VNodes. Note that VNodes created outside of the render function are not reactive.

export default {
  setup() {
    //...

    // ❌ non-reactive buttons array
    // let buttons = [base_offset.value, base_offset.value + 2, base_offset.value + 4]

    return () => {
      // ✅ reactive buttons array
      let buttons = [base_offset.value, base_offset.value + 2, base_offset.value + 4]

      return h(
        'ul',
        {
          class: 'pagination',
          onClick: (event) => {
            pageClick(event, 1)
          },
        },
        buttons
      )
    }
  }
}

demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.