gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:28:43 27 4
gpt4 key购买 nike

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

我有一个使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com