我有 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 文档:
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
)到他本地搜索
从事件字符串接收到的数据:
关于vue.js - 如何使该组件将其值传递给父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49109573/