vue.js - vue mixin 在实例和组件之间共享

标签 vue.js vue-mixin

我有一些我想在我的网站上共享的功能。我的网站确实有多个 Vue 实例,而不仅仅是一个应用程序实例入口点。

我已经像这样创建了我的 mixin:

var fooMixin = {
    data: {
        someProperty: null,
        someOtherProperty: "Foo"
    },
    methods{
       ...
    }
}

然后将这个 mixin 注入(inject)到我的 Vue 实例中,如下所示:
new Vue({
    el: '#app',
    mixins: [fooMixin],
    data: {
        ...
    },
    methods: {
        ...
    }
})

当然,这完全符合预期,但我的问题是我想在其他地方的组件中重用这个 mixin。这会导致问题。

以下是它注入(inject)组件的方式:
Vue.component('bar', {
    props: ['someProp'],
    template: barTemplate,
    mixins: [fooMixin],
    data: function () {
        return {
            mySpecialProperty: null
        }
    },
    methods: {
        ...
    }
})

可以想象,mixin 不能与 data 合并。组件的属性。由于这是一个组件,因此 data 属性必须返回一个返回对象的函数。这不是我的 mixin 的设置方式。

这是我从 Vue 得到的错误:

[Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions.



我可以创建一个可跨实例和组件重用的 mixin 吗?

最佳答案

将 mixin 中的数据属性从对象更改为函数

var mixin = {
  data: function () {
    return {
      someProperty: null,
      someOtherProperty: 'foo'
    }
  }
}

关于vue.js - vue mixin 在实例和组件之间共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56931056/

相关文章:

Vue.js/Mixins - 有没有办法在 vue 组件之外获取全局 mixin 对象?

typescript - 错误: [Vue warn]: Invalid handler for event "click": got undefined

javascript - b-modal 上的串联 id 不起作用(vue 和 bootstrap-vue)

javascript - 如何使用 Vue 实例中的全局混合方法

Javascript/Vue3 - Mixins - 默认返回 'null'

css - 在 Vuejs 中拥有全局 css 的最佳方式

vue.js - [Vue警告] : Error in render: “TypeError: Cannot read property ' xxx' of undefined”

javascript - Vue.js 在播放 Enter 后动态更改离开过渡

vue.js - 单击事件后从可组合项启动 useStore()