[Vuejs]-Conditional rendering: component or data

1👍

If I understand the problem correctly, you can solve this with a template. A template tag is not rendered.

<div id="root">
    <template v-if="!editModeOn">
      {{pageContent['mainContent']}}
    </template>
    <editable v-else :content="pageContent['mainContent']" />

    <label class="checkbox">
        <input type="checkbox" v-model="editModeOn">
        Switch edit mode
    </label>
</div>
👤Bert

1👍

Looking at the html, the contentId is hard-coded into the div, so I presume you’d have many such divs on the page. I’d make a component and pass in ‘content’ attribute.
Switching between edit and display can be with v-show

Vue.component('editable', {
  template: `
    <div>
      <div v-show="!editModeOn">{{ content }}</div>
      <div v-show="editModeOn">
        <input :value="content" @input="$emit('update:content', $event.target.value)"></input>
      </div>

      <label class="checkbox">
         <input type="checkbox" v-model="editModeOn">
        Switch edit mode
      </label>
    </div>
  `,
  props: ['content'],
  data {
    editModeOn: false
  }
})

On the main page

<editable :content.sync="pageContent['mainTitle']"></editable>    
<editable :content.sync="pageContent['mainContent']"></editable>

or perhaps

<editable v-for="item in pageContent" content.sync="item"></editable>    

Some notes:

Using v-show instead of v-if means the user can toggle back and forth between show and edit as desired, v-show keeps the edit in memory between mode but v-if destroys the edit node.

Using the .sync modifier allows the edits to be passed up to the parent, see .sync

I haven’t tested this, so it may need some tweaking, but you get the idea.
See working example codepen

Leave a comment