[Vuejs]-How to handle multiple components using the same v-model value

0👍

You will not solve it using only one campaign_target variable in simple way.

And I would suggest to keep it as simple as possible (KISS).

Use two variables for input and a computed value for campaign_target variable.

Here is the playground.

const { createApp, ref } = Vue;

const App = {
  data() {
    return {
      form: {        
        campaign_target_type: null,
        campaign_target_other: null
      },
      campaign_targets: [ 
      { id: 1, name: 'One'},
      { id: 2, name: 'Two'}, 
      { id: 3, name: 'Three'}
      ]    
    }
  },
  computed: {
    campaign_target() {
      return this.form.campaign_target_type == 'Other' 
        ? this.form.campaign_target_other 
        : this.form.campaign_target_type
    }
  }  
}

const app = createApp(App)
const vm = app.mount('#app')
#app { line-height: 2; }
[v-cloak] { display: none; }
<div id="app" v-cloak>
  <select v-model="form.campaign_target_type">
    <option
        v-for="target in campaign_targets"
        :value="target.name"
        :key="target.id"
    >
        {{ target.name }}
    </option>
    <option>Other</option>
  </select>

  <div v-if="form.campaign_target_type === 'Other'">
      <label class="font-semibold text-gray-700 text-sm mb-2 block">Enter Campaign Target</label>&nbsp;
      <input type="text" v-model="form.campaign_target_other" />
  </div>
  <p>campaign_target: {{ campaign_target }}</p>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

Leave a comment