VUE v-html不能触发点击事件的解决方案

背景:后端返前端html格式的数据,前端用v-html解析渲染,如:<a @click="show(1)"></a>,a标签能成功渲染,但其绑定的事件无法触发。

原因:vue没有将其作为vue的模板解析渲染

解决方案:不用v-html而是component模板编译

上干货:

<template>
    <div class="hello">
        <h1>
            我是父组件
        </h1>
        <div class="parent" id="parent">
        </div>
    </div>
</template>

<script>
    import Vue from 'vue';
    var MyComponent = Vue.extend({
        template: '<a @click="show(1)">我是大魔王</a>',
          methods: {     
            show(i) {
                console.log(i);
            },
        }
    });
    var component = new MyComponent().$mount();
    export default {
        data() {
            return {
            }
        },
        methods: {
        },
        mounted() {
            document.getElementById('parent').appendChild(component.$el);
        }
    }
</script>

<style scoped>
</style>

页面:
这里写图片描述
控制台:
这里写图片描述

如有帮助 欢迎点赞~

猜你喜欢

转载自blog.csdn.net/qq_31393401/article/details/81017912
今日推荐