我有一个简单的应用程序,可以捕获输入中的任何内容,并将其打印在 h1 中。
<div id="app">
<div>
<module v-on:button-pressed="parentPrint(capturedInput)"></module>
</div>
<h1>{{ h1Text }}</h1>
</div>
Run Code Online (Sandbox Code Playgroud)
问题是,h1 不会更新以反映输入值。
Vue.component('module', {
template:`
<div>
<input type="text" placeholder="Type Something Awesome" v-model="capturedInput" />
<button v-on:click="activateButtonPress">Change text</button>
</div>
`,
data(){
return {
capturedInput: ''
}
},
methods:{
activateButtonPress: function(){
console.log(this.capturedInput)
this.$emit('button-pressed', this.capturedInput)
}
}
})
new Vue({
el:'#app',
data:{
h1Text: 'Should reflect user input'
},
methods:{
parentPrint: function(capturedInput){
this.h1Text = capturedInput;
}
}
})
Run Code Online (Sandbox Code Playgroud)
我如何实际将数据传递到发射中并使其在父作用域中可用?capturedInput一直回来undefined找我。
当您在父级中定义事件处理程序时,您无需像现在这样添加参数。当您从孩子发出时传递的任何/所有参数都将发送给父母。
所以改变
<module v-on:button-pressed="parentPrint(capturedInput)"></module>
Run Code Online (Sandbox Code Playgroud)
到
<module v-on:button-pressed="parentPrint"></module>
Run Code Online (Sandbox Code Playgroud)
如果您只从您的孩子传递 1 个参数,就像您现在在 中一样this.$emit('button-pressed', this.capturedInput),只需在您正在调用的父方法中添加一个参数。如果您从子对象传递了 2 个参数,例如this.$emit('button-pressed', this.capturedInput, '2nd'),您只需在父方法定义中添加另一个参数来捕获它。
编辑:这个工作的代码笔:https ://codepen.io/anon/pen/rGmXbx
| 归档时间: |
|
| 查看次数: |
3793 次 |
| 最近记录: |