vue.js - 如何使该组件将其值传递给父组件?

标签 vue.js vuejs2 vuetify.js

我有 2 个组件 - 搜索过滤器和迭代器位于同一组件 App.vue 中,如下所示:

App.vue

<v-text-field 
  :search="search"
  v-model="search"
  label="type here to filter" 
>
</v-text-field>


<v-data-iterator
  :items="sortedContents"
  :search="search"
  v-model="selected"
>
  ...
</v-data-iterator>

...

data () {
  return {
    search: '',
  {
}

但后来我将该搜索过滤器移动到一个名为 <toolbar> 的单独组件中它内部的搜索过滤器不再起作用:

App.vue

<!-- this component contains the <v-text-field> -->
<toolbar :search="search"></toolbar>


<v-data-iterator
  :items="sortedContents"
  :search="search"
  v-model="selected"
>
  ...
</v-data-iterator>

...

data () {
  return {
    search: '',
  {
}

Codepen: https://codepen.io/anon/pen/ddEjgp?editors=1010


问题:

我应该在新的<toolbar>中添加什么组件以便将输入该搜索过滤器的数据传递给 App.vue 父组件?

最佳答案

您期望父组件可以使用更改后的 search 值,这是错误的。根据 vue 文档:

One-Way Data Flow

All props form a one-way-down binding between the child property and the parent one: when the parent property updates, it will flow down to the child, but not the other way around.

In addition, every time the parent component is updated, all props in the child component will be refreshed with the latest value. This means you should not attempt to mutate a prop inside a child component. If you do, Vue will warn you in the console.

您应该在工具栏的 v-text-field (@ input="onInput") 并发出一些事件 (this.$emit('filterinput', str)) 将数据弹出到父组件!父级应该监听(@filterinput="localSearchUpdate")该事件(codepen 中的filterinput)并更改(方法localSearchUpdate)到他本地搜索从事件字符串接收到的数据:

https://codepen.io/anon/pen/rJgqqv?editors=1010

关于vue.js - 如何使该组件将其值传递给父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49109573/

相关文章:

javascript - 从 vuex 存储访问 $vuetify 实例属性

javascript - 选择 ID 并显示名称

security - 将登录页面包含在单页应用程序中是否不安全?

vue.js - 如何通过 Vuex 和组合 API 在 Vue 中使用 v-model?

vue.js - Vuetify Autocomplete, item-slot , 保持字符高亮

javascript - vuex:未知 setter/getter :用户

vue.js - 如何使用 Prettier 禁用元素标签中的属性中断

vuejs2 - 在 laravel/vuejs2 项目中添加纯自定义 css 文件

vue.js - 如何在Vue中获取当前的路由名称?

sorting - 如何使用vuetify的自定义排序?