手把手教你实现一个简易的Vue组件在线编辑器

vue-cli使用过vue的我想大家都知道,那么xxx.vue组件是怎么运行的呢?怎么把template,script,style渲染到页面上的呢?今天我们手动写了个简易的Vue组件在线编辑器玩一玩。

准备工作

  1. 安装vuejs
  2. 新建xxx.html
  3. 新建xxx.css

编写页面

  <div id="app">
        <textarea name="" id="" cols="30" rows="30" v-model="content" autofocus placeholder="请输入vue模板"></textarea>
        <div class="btn-center">
            <button @click="run">运行代码</button>
            <button @click="reset">清除</button>
        </div>
    </div>
    <div id="result"></div>
    <script src="./node_modules/vue/dist/vue.js"></script>

textarea 元素为vue组件代码的编写部分,button为按钮区域

textarea {
            display: block;
            width: 100%;
            min-height: 100px;
            max-height: 500px;
            padding: 8px;
            resize: auto;
 }

 button {
            margin-top: 8px;
            display: inline-block;
            padding: 5px 16px;
            font-size: 14px;
            font-weight: 500;
            line-height: 20px;
            white-space: nowrap;
            vertical-align: middle;
            cursor: pointer;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
            border: 1px solid;
            border-radius: 6px;
            -webkit-appearance: none;
            -moz-appearance: none;
            appearance: none;
}
 .btn-center{
           text-align: center;
 }

思路分解

xxx.vue中,我们写组件通常遵循一下模板

<template>
    
</template>
<script>
export default {
    
}
</script>
<style>

</style>

我们想到的是在拿到输入的内容之后,我们希望获取都tempalte,script,style中的内容,然后通过Vue.extend( options )方法挂载到页面的元素上即可。

解析标签

我们需要拿到内容包括

<template>    </template>

<script>   </script>

<style>  </style>

可以利用字符串的match方法获取到每一段的开始标签的下标,开始标签的长度以及结束标签的下标,然后通过slice方法截取获取到想要的内容。

  getSource(type){
    const reg = new RegExp(`<${type}[^>]*>`);
    let content = this.content;
    let matches = content.match(reg);
    if(matches){
      let start = content.indexOf(matches[0])+matches[0].length;
      let end = content.lastIndexOf(`</${type}`);
      return content.slice(start,end)
    }
  },

转化函数

在vue官网中,data必须是一个函数,我们拿到的是一个字符串

export default {
    data(){
        return {
            msg:'hello world'
        }
    },
    methods:{
        run(){
            console.log("你好")
        }
    }
}

如何把一个字符串转化为可执行函数,可以参考如何让一个字符串执行?

我们可以用new Function方法将字符串转化为可执行函数,我们需要的是

data(){
        return {
            msg:'hello world'
        }
    },
    methods:{
        run(){
            console.log("你好")
        }
    }

利用字符串的replace方法将export default 替换成return得到

完成代码

 run:function(){
  let template = this.getSource("template");
  if(!template) return
  let script = this.getSource("script");
  if(script){
    script = script.replace(/export default/,"return");
  }
  let obj = new Function(script)();
  obj.template = template;
  let Profile = Vue.extend(obj);
  new Profile().$mount("#result")
 },

处理样式

通过正则解析拿到style样式之后,添加到head中即可

let styleCss = this.getSource("style");
let style = document.createElement("style");
style.innerHTML = styleCss;
document.head.appendChild(style);

总结

以上就是本文的全部内容了,只是简单地借助Vue.extend()方法实现的一个简单的Vue组件在线编辑器

   <div id="app">
        <textarea name="" id="" cols="30" rows="30" v-model="content" autofocus placeholder="请输入vue模板"></textarea>
        <div class="btn-center">
            <button @click="run">运行代码</button>
            <button @click="reset">清除</button>
        </div>
    </div>
    <div id="result"></div>
    <script src="./node_modules/vue/dist/vue.js"></script>
    <script>
        new Vue({
            el: "#app",
            data() {
                return {
                    content: ""
                }
            },
            methods: {
                getSource(type) {
                    const reg = new RegExp(`<${type}[^>]*>`);
                    let content = this.content;
                    let matches = content.match(reg);
                    if (matches) {
                        let start = content.indexOf(matches[0]) + matches[0].length;
                        let end = content.lastIndexOf(`</${type}`);
                        console.log(content.slice(start, end));
                        return content.slice(start, end)
                    }
                },
                run: function () {
                    let template = this.getSource("template");
                    if (!template) return
                    let script = this.getSource("script");
                    if (script) {
                        script = script.replace(/export default/, "return");
                    }
                    let styleCss = this.getSource("style");
                    let style = document.createElement("style");
                    style.innerHTML = styleCss;
                    document.head.appendChild(style);
                    let obj = new Function(script)();
                    obj.template = template;
                    let Profile = Vue.extend(obj);
                    new Profile().$mount("#result")
                },
                reset() {
                    this.content = ''
                }
            }
        })
    </script>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,下面是从零开始封装一个基于videojs和Vue的动态source的视频播放器组件的步骤: 1. 安装video.js和vue-video-player 使用npm安装video.js和vue-video-player: ``` npm install video.js vue-video-player --save ``` 2. 创建Vue组件 在src/components目录下创建一个VideoPlayer.vue的文件,该文件包含以下内容: ```html <template> <div> <video ref="videoPlayer" class="video-js vjs-default-skin vjs-big-play-centered"></video> </div> </template> <script> import videojs from 'video.js'; import 'video.js/dist/video-js.css'; import 'vue-video-player/src/custom-theme.css'; import 'vue-video-player/src/font/font.css'; import 'vue-video-player/src/assets/video-player.css'; export default { name: 'VideoPlayer', props: { sources: { type: Array, required: true }, options: { type: Object, default: () => ({}) } }, mounted() { this.initPlayer(); }, beforeDestroy() { if (this.player) { this.player.dispose(); } }, methods: { initPlayer() { const video = this.$refs.videoPlayer; const playerOptions = Object.assign({ controlBar: { children: { playToggle: {}, progressControl: {}, remainingTimeDisplay: {}, fullscreenToggle: {} } }, sources: this.sources }, this.options); this.player = videojs(video, playerOptions, function onPlayerReady() { console.log('Player ready'); }); } } }; </script> ``` 3. 在Vue项目中使用该组件 在需要使用视频播放器的Vue组件中引入VideoPlayer组件,并传入sources和options参数: ```html <template> <div class="app"> <VideoPlayer :sources="sources" :options="options"></VideoPlayer> </div> </template> <script> import VideoPlayer from '@/components/VideoPlayer.vue'; export default { name: 'App', components: { VideoPlayer }, data() { return { sources: [ { src: 'http://example.com/path/to/video.mp4', type: 'video/mp4' } ], options: { autoplay: false, controls: true, preload: 'auto', fluid: true } }; } }; </script> ``` 这样就完成了从零开始封装一个基于videojs和Vue的动态source的视频播放器组件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值