如何使 Vue js 指令在附加的 html 元素中工作 [英] How to make Vue js directive working in an appended html element

查看:29
本文介绍了如何使 Vue js 指令在附加的 html 元素中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在附加的 html 元素(如 v-on 指令)中添加了一个 Vue 指令,但它在我这边不起作用.基本上我想知道 jquery 中 .on() 的等价物.

解决方案

"Vue.js 编译发生在您实例化/挂载根实例时.它不会检测新的 DOM 被注入,除非它是指令的结果 (例如 v-repeat、v-partial 将动态创建新的 DOM 片段)."https://github.com/vuejs/Discussion/issues/77

您必须像这样编译新添加的元素:

html:

<button v-on="click: addNewElement()">添加元素</button><br/>

JavaScript

new Vue({el: '#app',数据: {sampleElement: '<button v-on="click: test()">Test</button>'},方法:{添加新元素:函数(){var element = $('#app').append(this.sampleElement);/* 编译新内容以便 vue 可以读取 */this.$compile(element.get(0));},测试:函数(){警报('测试');}}});

在 Firefox 上查看这个有效的 Fiddle : http://jsfiddle.net/chrislandeza/syewmx4e/

更新

$compile 已在 Vue 2.x

上删除

我看到有人建议 Vue.compile

var tmp = Vue.extend({模板:'内容'})new tmp().$mount('id 或 refs')

但是这两个不像旧的 $compile.

I have a Vue directive added in an appended html element like v-on directive but it's not working on my end. Basically I want to know the equivalent of .on() in jquery.

解决方案

"Vue.js compilation happens when you instantiate/mount the root instance. It doesn't detect new DOM being injected unless it is a result of a directive (e.g. v-repeat, v-partial will dynamically create new DOM fragments)." https://github.com/vuejs/Discussion/issues/77

You have to compile your newly added element like this:

html:

<div id="app">
    <button v-on="click: addNewElement()">Add Element</button> 
    <br />
</div>

JavaScript

new Vue({
    el: '#app',
    data: {
        sampleElement: '<button v-on="click: test()">Test</button>'
    },
    methods:{
        addNewElement: function(){

           var element = $('#app').append(this.sampleElement);
           /* compile the new content so that vue can read it */
           this.$compile(element.get(0));
        },
        test: function(){
           alert('Test');
        }
    }
});

See this working Fiddle on Firefox: http://jsfiddle.net/chrislandeza/syewmx4e/

Update

$compile has been removed on Vue 2.x

I've seen people suggesting Vue.compile or

var tmp = Vue.extend({ 
    template: 'Content'
})
new tmp().$mount(' id or refs ')

But those 2 does not behave like the old $compile.

这篇关于如何使 Vue js 指令在附加的 html 元素中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆