簡體   English   中英

有沒有辦法在VueJS中使用mixin繼承模板

[英]Is there way to inherit templates with mixins in VueJS

有人知道如何用它的模板繼承mixin嗎? 或者如何從mixin注入動態元素或組件?

編輯:我不想修改問候組件,我有兩個 Mixin: 404Mixin 添加一個方法 raise404() 並顯示一個 100% 層和 LoaderMixin 有 load() 方法在角落顯示一個微調器。 我可以繼承他們的方法,但我必須在我想要使用的每個組件中復制 html。

謝謝

 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 中創建組件 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>

您不能像示例中那樣“繼承”mixin 模板,如果可能的話,必須有一種合並模板的標准化方法。

既然你真正想要做的就是繼承模板,為什么不使用帶槽的組件組合呢?

 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>

您需要混合這些組件而不是將它們組合在一起有什么特別的原因嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM