javascript - Vue:如何将属性动态绑定到新的 DOM 元素
问题描述
说,我有一个带有以下模板的组件:
<div id="root"></div>
然后我以某种方式调用向其附加新元素的代码(现在使用 jQuery):
$('#root').append('<div id="a1" v-bind:styles="styles.a1"></div>')
其中“styles.a1”只是组件数据中的一个对象:
data() {
return {
styles: { a1: {color: 'red'} }
};
}
我想新元素的绑定不会起作用,因为 Vue 对这个新元素及其绑定一无所知。
但也许有一些方法可以实现所需的逻辑?
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/
使用自定义指令。
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); } });
推荐阅读
- typeorm - 覆盖 TypeORM 列选项
- visual-studio-code - vscode 中是否有本地 api 来按 glob 匹配文档文件?
- git - Git-LFS 在拉取过程中失败
- python - 映射数据框
- ssl - 无法使用 Let's Encrypt 证书通过 ldaps 连接到服务器
- c# - 来自 Azure 管道的 mongodb 超时错误 C#
- matlab - 我在哪里可以找到 MATLAB 映射工具箱中的所有数据?
- pyspark - 如何使用 pyspark 中的窗口应用重新分区?
- flutter-bloc - 状态相同但状态内容不同时如何使用flutter_bloc改变UI
- r - 为 R 中的 2d 网格插入 NA 值