【问题标题】:Vue.js - set slot content programmaticallyVue.js - 以编程方式设置插槽内容
【发布时间】:2017-11-22 16:11:47
【问题描述】:

有什么方法可以从组件内部设置/覆盖插槽的内容?喜欢

模板:

<div>
    <slot></slot>
</div>

JS:

export default {
    ...
     mounted() {
        this.$slot.render("<button>OK</button>");
     }
    ...
}

我知道我可以在我的元素上使用 v-html 将内容动态推送到组件模板中,但我的意思不仅仅是纯 HTML,我指的是带有 Vue 指令的 HTML。喜欢:

JS:

export default {
    ...
     mounted() {
        this.$slot.default.render('<button @click="submit">OK</button>');
     },
    methods: {
        submit() {
            // Here I want to get :)
        }
    }
    ...
}

基本上,我希望 Vue 在我的组件范围内渲染(像解析和渲染,而不像 innerHTML)某些字符串并放在我的组件中的某个位置。原因是我通过 AJAX 从服务器获取新内容。

很抱歉,经过 2 天的谷歌搜索,我仍然无法理解。

非常感谢!

【问题讨论】:

  • 可能不会。您最好的机会是在创建实际对象之前构建组件模板字符串(但它不支持任何更改)。这是一个非常糟糕的解决方案,因此您很可能应该考虑重构您的应用程序。
  • 感觉有点像对着框架工作

标签: vue.js


【解决方案1】:

我认为这是您最好的机会:即时构建您的组件。 在示例中,我使用了一个简单的占位符(使用 v-cloak)。

使用vue-router 在执行期间添加新创建的组件可能会获得更好的结果,使用router.addRoutes 这样您的应用就不必等待实例化整个 vue。

function componentFactory(slot) {
  return new Promise((resolve, reject) => {
    window.setTimeout(() => { // Asynchronous fetching
      resolve({ // Return the actual component
        template: `<div>
            ${slot}
          </div>`,
        methods: {
          submit() {
            console.log('hello');
          }
        }
      });
    }, 1000);
  });
}

componentFactory('<button @click="submit">OK</button>') // Build the component
  .then(component => {
    new Vue({ // Instantiate vue
      el: '#app',
      components: {
        builtComponent: component
      }
    });
  });
[v-cloak], .placeholder {
	display: none;
}

[v-cloak] + .placeholder {
	display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>

<div id='app' v-cloak>
  <built-component></built-component>
</div>
<div class="placeholder">
  This is a placeholder, my vue app is loading...
</div>

【讨论】:

    【解决方案2】:

    根据this,您可以通过编程方式实例化组件并插入插槽内容。

    import Button from 'Button.vue'
    import Vue from 'vue'
    var ComponentClass = Vue.extend(Button)
    var instance = new ComponentClass({
        propsData: { type: 'primary' }
    })
    instance.$slots.default = [ 'Click me!' ]
    instance.$mount() // pass nothing
    this.$refs.container.appendChild(instance.$el)
    

    【讨论】:

      猜你喜欢
      • 2018-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-06
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多