有没有办法在VueJS中使用mixins继承模板 [英] Is there way to inherit templates with mixins in VueJS

查看:65
本文介绍了有没有办法在VueJS中使用mixins继承模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何使用模板继承 mixin 吗?或者如何从 mixin 注入dinamically元素或组件?

Someone knows how inherit a mixin with its template? or how to inject dinamically elements or components from a mixin?

编辑:
我不想修改问候组件,我有两个Mixins:404Mixin添加方法raise404()并显示100%图层和LoaderMixin,其中有load()方法,显示角落中的微调器。我可以继承他们的方法,但我必须在我想要使用它的每个组件中复制html。

I don't want to modify greeting component, I have two Mixins: 404Mixin that adds a method raise404() and show a 100% layer and LoaderMixin that have loading() method that shows a spinner in the corner. I can inherit their methods, but I have to duplicate the html in every component that I want to use it.

谢谢

mixin = {
  template: '<p>{{ foo }}</p>',
  data() {
    return {
      foo: 'Hello',
    };
  },
}

// This should  be <div><p>Hello</p><p>World!</p></div>
Vue.component('greeting', {
  mixins: [mixin],
  template: '<div><p>World!</p></div>'
});

var vm = new Vue({
  el: '#app'
});

<script src="https://cdn.jsdelivr.net/vue/1.0.16/vue.js"></script>
<div id="app">
  <greeting></greeting>
</div>

推荐答案

你不能像你的例子那样继承mixin模板,如果有可能必须采用标准化方法来合并模板。

You can't "inherit" mixin templates like in your example, if it were possible there would have to be a standardized way of merging the templates.

因为看起来你真正想做的就是继承模板,为什么不在插槽中使用组件组合?

Since it seems all you really want to do is inherit the template, why not use component composition with slots?

Vue.component('not-found', {
  template: '#not-found',
  methods: {
    doSomethingSpecial() {
      alert('Hi there');
    },
  },
});

new Vue({
  el: '#app',
  data() {
    return {
      notFoundVisible: false,
    };
  },
});

.not-found {
  background-color: white;
  text-align: center;
  font-size: 30px;
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}

<script src="https://cdn.jsdelivr.net/vue/1.0.16/vue.js"></script>

<template id="not-found">
  <div class="not-found">
    <h1>404 Not Found</h1>
    <slot></slot>
  </div>
</template>

<div id="app">
  <not-found v-show="notFoundVisible" @click="notFoundVisible = false" v-ref:not-found>The resource was not found</not-found>
  <button @click="notFoundVisible = true">Click Me</button>
  <button @click="$refs.notFound.doSomethingSpecial()">Do Something Special</button>
</div>

为什么你需要混合这些组件而不是将它们组合在一起有什么特别的原因吗?

Is there any particular reason why you need to mixin these components instead of composing them together?

这篇关于有没有办法在VueJS中使用mixins继承模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆