vue函数式组件中的render函数如何添加伪类样式

问题描述

export default {
    functional: true,
    props: {
        data: {
            type: String,
            default() {
                return '';
            }
        },
        depth: {
            type: Number
        }
    },
    render: (h, ctx) => {
        return h('div', {
            class: ['treeitem'],
            style: {
                ':hover': {
                    background: 'yellow'  // 希望在div这个元素上添加一个伪类的样式,但是没有效果
                },
                height: '40px',
                lineHeight: '40px',
                border: '1px solid #f0f0f0',
                'marginLeft': ctx.props.depth*20 + 'px'
            },
            on: {
                click: () => {
                },
                mouseover: () => {
                }
            }
        }, [
            h('Icon', {
                props: {
                    type: 'arrow-right-b',
                },
                style: {
                    marginLeft: '20px',
                    display: 'inline-block',
                    width: '40px',
                    hight: '40px'
                }
            }),
            h('span',{
                style: {
                }
            }, ctx.props.data),
            h('Button', {
                props: {
                    icon: 'ios-gear-outline'
                },
                style: {
                    float: 'right' 
                },
                on: {
                    click: () => {
                    }
                }
            })
        ]);
    }
}

问题出现的环境背景及自己尝试过哪些方法

尝试为div元素添加class,但是作为函数式组件,这个是js文件,style该写在哪里?

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

你期待的结果是什么?实际看到的错误信息又是什么?

阅读 10.5k
3 个回答

这不是 vue 的问题,目前行内样式是不支持写伪类的

可以尝试在 head 中添加一个 style 标签

const styleEl = document.createElement('style')
styleEl.innerHTML = `
  .treeitem:hover{
    background: yellow;
  }
`
document.head.appendChild(styleEl)

推荐绑定到class上

推荐通过class来操作,然后通过class选中伪类

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题