我有一个nuxt.js应用程序,Child Component
当单击存在的按钮时,我想向存在的按钮(动态按钮)添加类名Parent Component
。我尝试使用Event Bus
,它能够将事件从父级发送到子级,但动态类未附加到按钮上。动态按钮将突出显示CSS
效果。任何建议或指南都将受到高度赞赏。
#父组件
<ChildComponent :id="id"/>
<button @click="sendMessageToChild()" class="btn btn-block btn-primary">Click Here</button>
methods: {
sendMessageToChild() {
this.$root.$emit('highlight')
},
}
<button class="btn btn-primary btn-block text-center rounded":class="{ highlight }">Buy</button>
<button class="btn btn-primary btn-block text-center rounded":class="{ highlight }">Buy</button>
<button class="btn btn-primary btn-block text-center rounded":class="{ highlight }">Buy</button>
<button class="btn btn-primary btn-block text-center rounded":class="{ highlight }">Buy</button>
data() {
return {
highlight: false,
timer: null,
}
},
mounted() {
this.$root.$on('highlight', () => {
this.highlight()
})
},
methods: {
highlight() {
this.highlight = true
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.highlight = false
}, 2000)
},
}
单击按钮后的#CSS效果Click Here
,应Child Component
在子组件中的#CSS中的所有动态按钮上突出显示
.highlight {
background:orange,
color:#fff;
border:1px #000 solid;
}
编辑后我的答案
父组件:
点击这里data() {
return {
highlight: false,
timer: null,
}
},
methods: {
sendMessageToChild() {
this.highlight = true
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.highlight = false
}, 2000)
},
}
.highlight {
animation: shake 1s cubic-bezier(0.36, 0.07, 0.19, 0.97) both infinite;
transform: translate3d(0, 0, 0);
backface-visibility: hidden;
perspective: 1000px;
}
子组件:
<button class="btn btn-primary btn-block text-center rounded":class="{ highlight }">Buy</button>
<button class="btn btn-primary btn-block text-center rounded":class="{ highlight }">Buy</button>
<button class="btn btn-primary btn-block text-center rounded":class="{ highlight }">Buy</button>
<button class="btn btn-primary btn-block text-center rounded":class="{ highlight }">Buy</button>
props: {
id: {
type: Number,
required: true,
},
highlight: {
type: Boolean,
required: false,
},
},
父组件和子组件之间的交互应该使用prop而非事件来完成,您可以highlight
在parent中定义为data属性,并将其作为prop传递给子组件:
父母:
<ChildComponent :id="id" :highlight="highlight"/>
<button @click="highlight" class="btn btn-block btn-primary">Click Here</button>
...
data() {
return {
highlight: false,
timer: null,
}
},
methods: {
highlight() {
this.highlight = true
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.highlight = false
}, 2000)
},
}
子组件:
<button class="btn btn-primary btn-block text-center rounded":class="{ highlight }">Buy</button>
<button class="btn btn-primary btn-block text-center rounded":class="{ highlight }">Buy</button>
<button class="btn btn-primary btn-block text-center rounded":class="{ highlight }">Buy</button>
<button class="btn btn-primary btn-block text-center rounded":class="{ highlight }">Buy</button>
...
props:["highlight"]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句