Vue.js - 以编程方式设置插槽内容

时间:2017-06-20 08:20:23

标签: vue.js

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

模板:

<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天的谷歌搜索,我仍然无法理解。

非常感谢!

2 个答案:

答案 0 :(得分:1)

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

tarefa: Tarefa =  {
  comentarios: '',
  data_tarefa: '',
  descricao: '',
  fim: '',
  id_aprovador: '',
  id_cliente: '',
  id_criador: '',
  id_sala: '',
  id_sistema: '',
  id_solicitante: '',
  inicio: '',
  nome_aprovador: '',
  nome_cliente: '',
  nome_criador: '',
  nome_sistema: '',
  nome_solicitante: '',
  numero: 0,
  participante: [],
  status_tarefa: 0,
  tarefa: '',
  tipoTarefa: {
      id:'',
      interna: null,
      descricao: ''
  }
};

答案 1 :(得分:0)

我认为这是您最好的机会:动态构建您的组件。 在这个示例中,我使用了一个简单的占位符(带有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>