【问题标题】:Vue v-model bind to Parent component input element doesn't workVue v-model绑定到父组件输入元素不起作用
【发布时间】:2021-07-01 04:32:47
【问题描述】:

我正在使用 Vue、Nuxt、Vue Good Table 实时搜索表格。我创建了一个名为child.vue 的子组件,并将其导入到父页面parent.vue。我使用v-modelsearchTerm 绑定到父组件中的input 元素上。当我运行它时,实时搜索不起作用。我从控制台收到警告。 Property or method "searchTerm" is not defined on the instance but referenced during render.你能帮帮我吗?我是 Vue.js 的新手。谢谢

对于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>

对于parent.vue

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

【问题讨论】:

    标签: vue.js vuejs2 nuxt.js vue-good-table


    【解决方案1】:

    将prop从parent传给child,并在parentsdata中定义searchTerm

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

    在child中定义prop,在childs中删除searchTermdata

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

    您现在可以访问子代&lt;template&gt; 中的searchTerm 或子代&lt;script&gt; 中的this.$props.searchTerm

    【讨论】:

      猜你喜欢
      • 2020-01-30
      • 2018-03-07
      • 2018-11-10
      • 1970-01-01
      • 2019-10-07
      • 2023-02-03
      • 2019-06-16
      • 2019-09-26
      • 1970-01-01
      相关资源
      最近更新 更多