简体   繁体   中英

How to access mixins in functional component in Vue?

I have a following mixin:

Vue.mixin({
    computed: {
        $_styles() {
            return { backgroundColor: "red" }
        }
    }
})

Then, I have following functional component:

<template functional>
    <!-- $_styles doesn't work -->
    <div style="height: 100px; width: 100px;" :style="$_styles">
    </div>
</template>

How do I actually access global variable, in this case it's $_styles , inside functional component?

You cannot do this with a template-based functional component but if you define your render function, you can manipulate the context.data.style property, including pulling the mixin values from the context.parent component.

 Vue.mixin({ computed: { $_styles() { return { backgroundColor: 'red' } } } }) Vue.component('func-component', { functional: true, render (createElement, context) { const style = { height: '100px', width: '100px', ...context.parent.$_styles // get mixin styles from parent component } return createElement('div', { ...context.data, style // override context.data.style }, context.children) } }) new Vue({el: '#app'}) 
 <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script> <div id="app"> <func-component></func-component> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM