javascript - Vue Mixin 属性为空白/空/非响应式(Reactive)

标签 javascript vue.js axios

我希望这个问题不是重复的。如果是这样,请给我指出正确的方向。

我有一个使用 Webpack@NPM 编译的 Vue 应用程序。我使用 mixin 在所有组件中传播属性 ( roles )。我使用应用程序实例化中的 ajax 调用来更新它。问题是roles仅更新 <Root>组件,不适用于所有其他组件。

////////////////////////
// app.js
////////////////////////

// import
window.axios = require('axios')
import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes.js'

// mixin
Vue.mixin({
    data: function () {
        return {

            // property in question
            roles: [],
        }
    },

    methods: {
        getRoles: function() { //////////// this method updates property.
            // get
            axios.get('/api/vcr/admin/roles')

            // process
            .then(response=>{
                this.roles = response.data.data;
            })

            // error?
            .catch(error=>{
                this.toast(error.response.data.message);
            })
        },
    },
});

// router
const router = new VueRouter({
    mode: 'history',
    routes:  routes,
});

// app
const app = new Vue({
    el: '#app',
    components: { App: require('./views/App').default },
    router,
    base: '/saas/vcr/admin',

    created: function() { ////////////// I update it here
        this.getRoles();
    }
});

////////////////////////
//  Foo.vue
////////////////////////

<script>
    export default {
        mounted: function() {
            console.log(this.roles) ////// returns an empty array
        }
    }
</script>

你知道怎么做roles react 性?

最佳答案

您创建的全局 mixin 不会调用填充 roles 属性的函数,它依赖于继承实例来执行此操作。在您的 app “root”实例中,您在 created 生命周期钩子(Hook)中执行此操作,该钩子(Hook)在 mixin 上调用 getRoles ,但是在您没有调用组件 Foo,因此它将具有默认的空值。 roles 属性不共享,每个组件都会获得自己的副本,并且需要填充。

您可以更改 mixin 来为您执行此操作,方法是添加生命周期 created Hook ,就像在根实例中所做的那样。 Here's一个例子。请注意,在混合中实现这一点不会阻止或覆盖稍后的生命周期 Hook 在其合并到的实例上运行。但是,在您的情况下,它会对创建的每个组件实例进行 API 调用,这可能是不可取的。

如果您只想填充一次然后在所有组件之间共享它,那么使用 Vuex 并拥有一个全局状态可能更有意义,其中 roles 集中填充并在一个中的所有组件之间共享响应式(Reactive)方式。

关于javascript - Vue Mixin 属性为空白/空/非响应式(Reactive),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58977097/

相关文章:

javascript - 将 HTML 表格传递给 Google 电子表格。从动态表中获取单元格值

javascript - 使用表格的导航滚动不起作用

vue.js - VueJS CKeditor5上传图片

javascript - Vue中如何访问子组件数据

javascript - 如何模拟 axios.all 请求?

javascript - 为什么请求头没有在 react 中的get请求中传递?

JavaScript 换行符

javascript - 如果用户滚动,则出现在中间的 Div 会中断

javascript - Vue.js 单文件组件无法按预期工作

javascript - 使用 "nested"获取设置钩子(Hook)时,React、Axios、PokeAPI 返回未定义