vue.js - Vuejs从父到子传递函数
问题描述
我有一个关于将功能从父母传递给孩子的初学者问题。在我的例子中,我想更多地使用孩子,有时它应该做其他事情v-on:focus
。我怎样才能做到这一点?有一些选项可以用 prop 传递它,但我不知道怎么做,我认为这样做不好?也许使用 EventBus,如果是,那么如何?我想知道如何在 VueJs 中做到这一点的正确方法。
这是父组件:
import Child from "./child.js";
export default {
name: "app",
components: {
Child
},
template: `
<div>
<child></child>
<child></child>
<child></child>
</div>
`
};
这是子组件:
export default {
name: "test",
template: `
<div class="form-group">
<div class="input-group">
<input v-on:focus="functionFromChild">
</div>
</div>
`,
methods: {
functionFromChild() {
//run the function from parent
}
}
};
解决方案
您可以将函数作为任何其他道具传递
import Child from "./child.js";
export default {
name: "app",
components: {
Child
},
methods: {
calledFromChild(id){
console.log(id)
}
},
template: `
<div>
<child :callback="calledFromChild" id="1"></child>
<child :callback="calledFromChild" id="2"></child>
<child :callback="calledFromChild" id="3"></child>
</div>
`
};
然后在孩子
export default {
name: "test",
props: ["callback", "id"],
template: `
<div class="form-group">
<div class="input-group">
<input v-on:focus="() => this.calledFromChild(this.id)">
</div>
</div>
`,
}
我还为孩子添加了一个 ID,以便您知道哪个孩子正在拨打电话。
但这不是一个好主意。您应该使用从您的孩子发出的事件来发送一个事件,并从父母那里收听它。
在孩子
export default {
name: "test",
template: `
<div class="form-group">
<div class="input-group">
<input v-on:focus="handleFocus">
</div>
</div>
`,
methods: {
handleFocus() {
this.$emit('focusEvent')
}
}
};
而在父母
<child @focusEvent="handleFocusFromChild"></child>
这里是一个工作示例
推荐阅读
- django - 即使用户名已经存在,Django 表单也会更新前端
- ruby-on-rails - 更改 Rails 日期类型格式
- ios - OneSignal 推送通知链接返回到应用程序
- ios - 从一个 ViewController 中的文本字段获取输入并在另一个类中使用
- javascript - 获取未捕获的 ReferenceError:当我尝试在测验中单击我的答案选项之一时未定义 checkAnswer
- python - Python Pandas 基于另一列的唯一列值计数
- python - Python Tweepy:遍历光标的项目时出现 Tweepy 错误
- gravitee - 无法在 gravitee 中找到集群名称配置
- c# - 带静态场的闭包
- python-3.x - 从字典字典中仅获取空的子字典值