[Vuejs]-Vue the same component tag name will impact by other data source

0👍

Changing a component’s template within another component is going to change the definition globally and is bad practice.

You should initially register two components, one for each template:

Vue.component("my-component-1", { template: "<p>TEMPLATE01</p>" });
Vue.component("my-component-2", { template: "<p>TEMPLATE02</p>" });

Change your Vue instance’s data properties to include the two component names instead of the templates:

data: {
  sections: sections,
  components: ['my-component-1', 'my-component-2']
},

Change your v-for to loop through the new components array instead:

<option v-for="component in components" :value="component">{{ component }}</option>

And, finally, change the displayed component to be a dynamic component using the :is directive to bind the type of component to the selected option:

<component :is="s.selected_option"></component>

Here’s a working codepen.

Leave a comment