首页 > 解决方案 > 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,但这是我必须处理的情况。

标签: javascriptjqueryvue.jsvuejs2

解决方案


如果您使用的是 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);
        }
    });
    
    

推荐阅读