4

I am changing my code from the template file to the render function. Now I have this HTML:

:open.sync="state"

But I don't know how to translate this to JavaScript. How to write this to the createElement function?

5
  • can you share vue.sync live demo or snippet example ? Commented Apr 26, 2018 at 11:39
  • here is the documentation vuejs.org/v2/guide/components-custom-events.html#sync-Modifier I will post a example Commented Apr 26, 2018 at 11:41
  • It's just a combination of a v-bind and a v-on:update. Can you do each of those? Commented Apr 26, 2018 at 12:00
  • @RoyJ I don't know how to implement v-on:update in the javascript render function Commented Apr 26, 2018 at 12:15
  • stackoverflow.com/questions/48219897/… Commented Apr 26, 2018 at 12:51

2 Answers 2

14

Remember that

:open.sync="state"

is basically syntax sugar for

:open="state" @update:open="state = $event"

Then the equivalent in the render function would be:

createElement('child', {
  props: {                                   // :open="state"
    "open": this.state
  },
  on: {                                      // @update:open="state = $event"
    "update:open": ($event) => {
      this.state = $event;
    }
  }
})

Demo:

Vue.component('child', {
  template: '#child',
  props: ['open']
})

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
  render(createElement) {
    return (
      createElement('div', [
        this.message,
        createElement('br'),
        createElement('child', {
          props: {
            "open": this.message
          },
          on: {
            "update:open": ($event) => {
              this.message = $event;
            }
          }
        })
      ])
    );
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ message }}</p>
  <child :open.sync="message"></child>
</div>

<template id="child">
  <div>
    <input type="text" :value="open" @input="$emit('update:open', $event.target.value)">
    open: {{ open }}
  </div>
</template>

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

Comments

0

As March 2021 && From @acdcjunior inspiration I've came up with this solution:

// From Parent 
<custom-input
  :open.sync="formData.groupName"
/>
// CHILD
<div class="wrapper">
      <input
        type="text"
        class="full-width"
        :value="open" @input="$emit('update:open', $event)"
      />
</div>

BTW: His solutions wasn't working since $event.target.value was undefined.

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.