我创建了一个我多次重复使用的“盒子”组件。每个元素都有一个父级监听的@mouseenter 事件。我的目标是更改子元素的边框颜色。因为我用循环从父级声明了我不能只更改一个子属性,但它们都会改变
<template>
<div>
<div id="container">
<div id="row" v-for="i in 11" :key="i">
<div>
<box-component v-for="j in 7" :key="j" :color="getColor(i, j)" v-bind:borderColor="getBorder(i, j)" :row="i" :col="j" v-on:changeBorder="highlightBorder($event)"></box-component>
</div>
</div>
</div>
</div>
</template>
问题出在这部分:
v-bind:borderColor="getBorder(i, j)"
因为 i 和 j 改变了我不知道如何只影响一个 child 。
我知道我可以删除循环并复制粘贴相同的代码,但必须有另一种解决方案。我也知道这个特定示例可以直接在子组件上实现,但我需要能够从父组件上实现。
最佳答案
你可以这样做:
<box-component v-on:change-border="highlightBorder(i, j)"></box-component>
来自 the docs :
Unlike components and props, event names will never be used as variable or property names in JavaScript, so there’s no reason to use camelCase or PascalCase. Additionally,
v-on
event listeners inside DOM templates will be automatically transformed to lowercase (due to HTML’s case-insensitivity), sov-on:myEvent
would becomev-on:myevent
– makingmyEvent
impossible to listen to.For these reasons, we recommend you always use kebab-case for event names.
互动演示
Vue.component('parent-component', {
template: '#parent-component',
data() {
return {
defaultStyles: {
color: '#555',
borderColor: '#bbb'
},
highlightedStyles: {
color: '#f50',
borderColor: 'orange'
},
highlighted: {x: null, y: null}
};
},
methods: {
isHighlighted(x, y) {
return x === this.highlighted.x && y === this.highlighted.y;
},
getStyles(x, y) {
return this.isHighlighted(x, y) ? this.highlightedStyles : this.defaultStyles;
},
getColor(x, y) {
return this.getStyles(x, y).color;
},
getBorder(x, y) {
return this.getStyles(x, y).borderColor;
},
highlightBorder(x, y) {
this.highlighted = {x, y};
}
}
});
Vue.component('box-component', {
template: '#box-component',
props: ['color', 'borderColor']
});
var vm = new Vue({
el: '#app'
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.row:after {
content: '';
display: block;
clear: both;
}
.box {
float: left;
padding: .5em;
border-width: 4px;
border-style: solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>
<div id="app">
<parent-component></parent-component>
</div>
<template id="parent-component">
<div>
<div id="container">
<div class="row" v-for="y in 11" :key="`row-${y}`">
<div>
<box-component
v-for="x in 7"
:key="`cell-${x}`"
:color="getColor(x, y)"
:border-color="getBorder(x, y)"
:col="x" :row="y"
@change-border="highlightBorder(x, y)"
></box-component>
</div>
</div>
</div>
</div>
</template>
<template id="box-component">
<div
class="box"
:style="{background: color, borderColor: borderColor}"
@mouseenter="$emit('change-border')"
></div>
</template>
关于javascript - Vue.js 在悬停时更改子组件的 css 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53905843/