刚开始是想通过父组件修改element-ui中的某个元素的样式。由于动态添加class不够方便,所以想通过$refs,根据类名选择出元素,做法如下
App.vue
<template>
<div>
<Student ref="student"></Student>
<button @click="changeColor">改变背景</button>
</div>
</template>
<script>
import Student from './components/Student';
export default {
components: { Student },
methods: {
changeColor() {
// 通过$refs选择子组件,$el选择元素数组,
// 每个元素中有className是类名字符串(如'son1 son2')
// 通过遍历循环判断出对应的元素,然后通过style修改
this.$refs.student.$el.childNodes.forEach((item) => {
if (item.className.indexOf('el-button--default') !== -1) {
item.style.backgroundColor = 'red';
}
});
},
},
};
</script>
Student.vue
<template>
<div>
<el-button>默认按钮</el-button>
<el-button type="primary">主要按钮</el-button>
<el-button type="success">成功按钮</el-button>
<el-button type="info">信息按钮</el-button>
<el-button type="warning">警告按钮</el-button>
<el-button type="danger">危险按钮</el-button>
</div>
</template>
<script>
export default {};
</script>