Vue Mixin特性为空白/空/无反应性



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

我有一个Vue应用程序,它是用Webpack@NPM.我使用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反应吗?

您创建的全局mixin不调用填充roles属性的函数,它依赖于继承实例来调用。在app"根"实例中,您在created生命周期挂钩中调用mixin上的getRoles,但在组件Foo中,您没有调用它,因此它将具有默认的空值。roles属性不共享,每个组件都将获得其自己的副本,并且需要填充。

您可以像在根实例中那样,通过添加生命周期created钩子来更改mixin以实现这一点。这是一个例子。请注意,在mix-in中实现这一点不会阻止或覆盖稍后的生命周期挂钩在其合并到的实例上运行。但是,在您的情况下,它将对创建的每个组件实例进行API调用,这可能是不可取的。

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

最新更新