花括号匹配变量组件实现记录,vue字符串渲染成组件的两种方式

2,863 阅读2分钟

需求

最近遇到一个需求是:

input 框需要支持输入双花括号来引用变量({{变量名}}),鼠标移入花括号时要弹框显示变量信息(类似 postman 匹配变量的效果)

从技术上说就是需要从输入的字符串中匹配 {{变量名}} 替换成 element 的弹框组件 el-popover,实现 hover 时显示弹框信息

实现方案

因为 input 中不能渲染 html 或者说组件,那么我需要设置一个 input 一个 div,

input 用来输入内容,在 blur 时,替换内容中的 {{}} 为 el-popover 组件,然后在 div 中渲染,显示 div 隐藏 input ,

点击 div 时,再切换为显示 input,隐藏 div,并调用 input 的 focus 方法,光标回到末尾

下面记录下这个组件实现的几个要点

字符串渲染成组件

将字符串渲染为组件,用 v-html 不就可以了吗?其实是不行的,v-html 只能渲染 html 标签。

要把字符串渲染成组件,需要使用 template

<template>
    <component :is="component"></component>
</template>

<script>
export default {
    data() {
        return {
            component: null
        }
    },
    methods: {
        render() {
            this.component = {
                data() {
                    return {
                        test: 1
                    }
                },
                template: '<div><el-popover></el-popover><div>'
            }
        }
    }
}
</script>

写完之后,你会发现有个报错,那是因为 vue 默认不引入编译器的,参考文档

You are using the runtime-only build of Vue where the template compiler is not available. 
 Either pre-compile the templates into render functions, or use the compiler-included build.

要解决报错,开启编译器即可

// vue-cli3
// 在 vue.config.js 中设置 runtimeCompiler
module.exports = {
    runtimeCompiler: true
}

// nuxt
// 在 nuxt.config.js build 中拓展配置
build: {
    extend(config) {
      config.resolve.alias['vue$'] = 'vue/dist/vue.esm.js'
    }
}

这里把字符串渲染成组件除了 template 外还有另外一种方法就是使用 Vue.compile,这个同样是需要引入编译器的

模拟 placeholder

使用 css 表达式 attr

<div class="input" placeholder="请输入"></div>

.input:before {
    content: attr(placeholder);
    color: #bbb;
}

设置光标回到字符尾部

对于 contenteditable 设为 true 的可编辑 div,调用 focus 方法后,光标是在第一位的。

要把他放到最后,可以使用 RangeSelection API。简单来说,Selection 包含 Range,比如你在浏览器选中一段文字,按住 ctrl 再选中另一段文字,那么就等于有两个 Range 在 Selection 中,具体的方法和属性查看文档即可

那么光标回到最后可以这么写

const range = document.createRange() // 创建 range 实例
range.selectNodeContents(this.$refs.divInput) // range 包含某个元素
range.collapse(false) // 折叠 range 至末位(传 true 为首位)
const slection = window.getSelection() // 创建 selection 实例
slection.removeAllRanges() // 清掉其所有 range
slection.addRange(range) // 塞入刚刚的 range 实例

对于 input ,设置光标回到尾部,可以直接调用 setSelectionRange

const valueLength = this.value.length
this.$refs.input.setSelectionRange(valueLength, valueLength)

参考

博客

渲染 String 为 组件

文档

CSS 表达式 attr

setSelectionRange

Range

Selection