Chang Day
Chang Day

Reputation: 33

Vue v-model bind to Parent component input element doesn't work

I am using Vue, Nuxt, Vue Good Table to live search a table. I create a child component named child.vue, and imported it into the parent page parent.vue. I used v-model to bind the searchTerm on the input element in the parent component. When I run it, live search doesn't work. And I got an warning from the console. Property or method "searchTerm" is not defined on the instance but referenced during render. Could you please help me out? I am new to Vue.js. Thank you

For the child.vue

<template>
<vue-good-table
    :columns="columns"
    :rows="rows"
    :search-options="{
      enabled: true,
      externalQuery: searchTerm
    }"
    :sort-options="{
      enabled: false,
    }"
    :group-options="{
      enabled: true, 
    }"
  />
</template>
<script>
export default {
    name: 'my-component',
    data() {
        return {
            searchTerm: '',
            columns: [xxxx]
        }
    }
}
</script>

For the parent.vue

<template>
  <div>
    <input type="text" placeholder="Live Search" v-model="searchTerm" />
  </div>
  <div>
    <child />
  </div>
</template>

Upvotes: 1

Views: 678

Answers (1)

tauzN
tauzN

Reputation: 6951

Pass the prop from the parent to the child, and define searchTerm in the parents data

<template>
...
  <input type="text" placeholder="Live Search" v-model="searchTerm" />
  <child :searchTerm="searchTerm" />
...
</template>
<script>
  data(){
    return {
      searchTerm: ''
    }
  }
...
</script>

Define the prop in the child, and remove searchTerm in the childs data

<script>
export default {
  ...
  props: ['searchTerm'],
  ...
  data(){
    return {
      //searchTerm: '' <- remove this from child
    }
  }
   ...
}
</script>

You can now access searchTerm in the childs <template> or this.$props.searchTerm in the childs <script>

Upvotes: 1

Related Questions