Javascript vuejs:事件的v-if指令?
我可以对vue模板中的事件作出反应吗?假设子组件分派事件Javascript vuejs:事件的v-if指令?,javascript,vue.js,Javascript,Vue.js,我可以对vue模板中的事件作出反应吗?假设子组件分派事件$dispatch('userAdded'),我可以在父组件中执行类似的操作吗: <div class="alert alert-info" v-if="userAdded"> User was created! </div> 是的,你可以,但你需要采取这种方法 创建分派事件的子级 在父组件中,为事件创建一个事件监听器,以及事件监听器将在组件实例上本地设置的数据属性 在父级中,将v-if绑定到本地数据组件
$dispatch('userAdded')
,我可以在父组件中执行类似的操作吗:
<div class="alert alert-info" v-if="userAdded">
User was created!
</div>
是的,你可以,但你需要采取这种方法
事件的整体理念是你可以对它们做出反应。但是你想让反应通过模型。你真的不想让无关的标记“独立”地听和反应$不推荐使用dispatch。要立即执行此操作,请执行以下操作 在子组件中,发出一个事件,如下所示
this.$emit('didIt' {wasItAwful:'yep',wereYouScared:'absolutely'});
在父级中,将事件侦听器注册为v-on,作为子级标记的属性
<adventure-seeking-child v-on:did-it='myChildDidIt' />
文档是。是
表单。成功
部分数据,您的addView
组件中计算的道具或道具?为什么不发送一个包含您需要的孩子信息的事件?@nils:表单。成功的是我在addView
中的数据的一部分component@eltonkamami:然后将该信息写入父级的数据
?如果有更简单的方法,这就是我试图避免的。@Chris,正如我从您的代码中理解的,child处理创建,parent显示成功消息。您可以将父函数作为道具传递给子函数,并在用户创建时调用它。要么将属性预定义为parentsdata
,要么使用this创建它。$set
在飞行中想到这一点,希望有一种更直接的方法。不过我还是接受了你的回答:)。谢谢你的回复。@Chris-用双向道具更新了答案
Vue.directive('hide-after', {
update: function(value) {
setTimeout(() => this.el.remove(), value);
}
});
<div class="alert alert-info" v-hide-after="2000">
This will be shown for 2 seconds
</div>
<div v-if="showAlert"></div>
events: {
'alert.show': function () {
this.showAlert = true
},
'alert.hide': function () {
this.showAlert = false
}
},
data () {
return {
showAlert: false
}
}
methods: {
showAlert (show) {
show ? this.$dispatch('alert.show') : this.$dispatch('alert.hide')
}
}
<div v-if="showAlert"></div>
<child-component :show-alert.sync="showAlert"></child-component>
data () {
return {
showAlert: false
}
}
props: {
showAlert: {
type: Boolean,
twoWay: true
}
},
methods: {
showAlertInParent (show) {
this.$set('showAlert', show)
}
}
this.$emit('didIt' {wasItAwful:'yep',wereYouScared:'absolutely'});
<adventure-seeking-child v-on:did-it='myChildDidIt' />
methods : { myChildDidIt : function(payload){ ... } }