代码之家  ›  专栏  ›  技术社区  ›  Hans Yulian

如何从Vue获得ViewModel:IS

  •  0
  • Hans Yulian  · 技术社区  · 7 年前

    <template id="test-button-component">
        <div class="test-button__container">
            This is test button
            <button @click="clickButton">{{buttonTitle}}</button>
        </div>
    </template>
    
    <template id="test-button-component2">
        <div class="test-button__container">
             <button></button>
        </div>
    </template>
    

    :is 绑定按名称进行组件绑定,如下所示:

    <div :is='myComponentName' ></div>
    

    myComponentName

    1 回复  |  直到 7 年前
        1
  •  1
  •   thanksd thibaut noah    7 年前

    您可以添加 ref attribute ref="custom" <div> 动态组件的标记。然后通过引用组件实例 this.$refs.custom

    is 道具更改:

    new Vue({
      el: '#app',
      data() {
        return { 
          value: 'foo',
          children: {
            foo: { 
              name: 'foo',
              template: '<div>foo</div>',
              data() { 
                return { value: 1 };
              }
            },
            bar: {
              name: 'bar',
              template: '<div>bar</div>',
              data() { 
                return { value: 2 };
              }
            }
          }
        }
      },
      computed: {
        custom() {
          return this.children[this.value];
        }
      },
      watch: {
        custom() {
          this.$nextTick(() => {
            console.log(this.$refs.custom.$data)
          });
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
    <div id="app">
      <select v-model="value">
        <option>foo</option>
        <option>bar</option>
      </select>
      <div :is="custom" ref="custom"></div>
    </div>

    $data 组件参考 $refs.custom $nextTick handler