比如说,我有一个具有以下模板的组件:
<div id="root"></div>
然后我以某种方式调用将新元素附加到它的代码(现在使用 jQuery):
$('#root').append('<div id="a1" v-bind:styles="styles.a1"></div>')
其中“styles.a1”只是组件数据中的一个对象:
data() {
return {
styles: { a1: {color: 'red'} }
};
}
我想新元素的绑定(bind)将不起作用,因为 Vue 对这个新元素及其绑定(bind)一无所知。
但也许有一些方法来实现所需的逻辑?
PS 我知道 Vue 的本质是处理数据,而不是 DOM,但这是我必须处理的情况。
最佳答案
如果您使用的是 Vue 组件,则不应操作 DOM。
您应该为此使用模板逻辑。
<template v-if="someCondition"> <div id="a1" v-bind:styles="styles.a1"></div> </template>
将非 Vue 代码包装在它自己的 Vue 组件中。
Vue.component('date-picker', { template: '<input/>', mounted: function() { $(this.$el).datepicker(); }, beforeDestroy: function() { $(this.$el).datepicker('hide').datepicker('destroy'); } });
https://vuejsdevelopers.com/2017/05/20/vue-js-safely-jquery-plugin/
使用 custom directive .
Vue.directive('demo', { bind: function () { $(this.el).css({color:'#fff', backgroundColor:this.arg}); }, update: function (value) { $(this.el).html( 'argument - ' + this.arg + '!<br>' + 'key - ' + this.key + '<br>' + 'value - ' + value); } });
关于javascript - 视觉 : How to bind property dynamically to a new DOM element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55035222/