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

EDIT:

谢谢

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>

推荐答案

多年后,我可以想象一个优雅的解决方案,也许使用类、typescript或在mixin中创建组件super的注释会更优雅,但现在,问题已经部分解决了.

GreetingMixin = {
  data() {
    return {
      greeting: 'Hello',
    };
  },
  provide() { return {child: this}},
  components: {
    super: {
      inject: ['child'],
      template: '<div class="blue">{{ child.greeting }} <strong><slot /></strong></div>',
    }
  },
}


// This should be <div class="blue">Hello <strong>World!</strong></div>
Vue.component('welcomeWorld', {
  mixins: [GreetingMixin],
  template: '<super>World!</super>',
});

// This should be <div class="blue">Hi <strong><i>ali</i></strong></div>
Vue.component('welcomeName', {
  mixins: [GreetingMixin],
  props: ["name"],
  created() { this.greeting = "Hi" },
  template: '<super><i>{{ name }}</i></super>',
});

// This should be <h1><div class="blue">Hello <strong>World</strong></div></h1>
Vue.component('welcomeH1', {
  mixins: [GreetingMixin],
  props: ["name"],
  template: '<h1><super>{{ name }}</super></h1>',
});


var vm = new Vue({
  el: '#app'
});
.blue {
color: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <welcome-world></welcome-world>
  <welcome-name name="Ali"></welcome-name>
  <welcome-h1 name="Ali"></welcome-h1>
</div>

Vue.js相关问答推荐

为什么我的数组在 onBeforeMount 函数中不为空,但在 onMounted 函数中为空

如何在Vue3中使用vuechartjs 5.2从父组件更新图表

如果似乎没有明确使用输入事件,那么发出输入事件有什么作用?

在 VueJS 中,将变量而不是组件的字符串名称传递给动态组件的 :is 属性不起作用

vue js导航到带有问号的url

Webpack 导入的模块不是函数

将函数作为属性传递给 Vue 组件

Vuejs 和 Laravel 发布请求 CORS

如何从 Vuex 状态使用 Vue Router?

Vuelidate 判断true/false

动态插入字符串上的 Vue 事件处理程序不起作用

如何在 vue.js 中包含当年的版权?

在 SASS 中使用 Vuetify 类

Vuejs 2,VUEX,编辑数据时的数据绑定

在 v-for 循环中使用 v-model

我在 Nuxt 2.14.0 中运行的是什么版本的 Vue?

了解 Nuxt.js 中的State状态和Getters:Getters不起作用

如何在 Vue.js 中延迟 @keyup 处理程序

无法访问手表处理程序 vuejs 中的数据变量

vuejs 中缺少 webpack 配置