vue js 2:在挂载函数中访问道具 [英] vue js 2: Access props in mounted function

查看:20
本文介绍了vue js 2:在挂载函数中访问道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在子组件中有数据道具.在已安装函数的子组件中,我需要从 props 获取特定值并设置选择下拉值.我正在使用 vue-multiselect 插件,它工作正常.这是代码.

I have data props in child components. Inside child component on mounted function I need to get specific value from props and set select dropdown value. I am using vue-multiselect plugin which is working fine. Here is the code.

module.exports = {
    props: ["Subscriptions"]
    mounted: function () {
        let vm = this;      


        Vue.nextTick(function () {      
        // I want to access props here but it return 0 length array 
            console.log(vm.$parent.Subscriptions);
        });
    },  
    beforeUpdate() {
        let vm = this;
        console.log(vm.$parent.Subscriptions);
    },
//  updated() {
//      let vm = this;
//      console.log(vm.$parent.Subscriptions);
//  }
};

现在只有在我获得订阅的时候才在 beforeUpdate 和 updated 函数中,但是每次发生不需要的值更改时都会调用它.我只需要第一次更改它以设置下拉初始值.

Now only time I do get subscriptions is in beforeUpdate and updated function but this called each time there is a change in value which is not required. I only need to change it first time in order to set drop down initial value.

推荐答案

一个常见的错误可能是,父组件将一个变量作为 prop 传递,在子组件被渲染的那一刻它为 null.因此,当您在安装在子组件中访问它时.您将其视为空值.稍后,在 Parent 组件中,传递的变量 (prop) 将从异步操作中分配值.为了避免可能的陷阱,最好使用 v-if.

A common mistake could be, parent component pass a variable as a prop which is null at the moment where child component get rendered. Thus when you access it in mounted in child component. You see it as a null value. And at a later time, in Parent component the variable which was passed (prop) will be assign the values from an asynchronous operation. To avoid possible pitfalls, better to use v-if.

示例:

<ChildComponent :data="testData" />

可以使用下面的代替上面的

instead of above below can be used

<ChildComponent v-if="testData" :data="testData" />

这样只有当 testData 可用时才会呈现子组件.但是如果在子组件中你有更多的东西要显示,直到数据更好地使用另一个组件.添加观察者也可以解决问题,但不是很好.

so that only when testData available child component will be rendered. But if in child component you have some more things to show until data comes in better to use another component. And adding watchers will also resolve the problem but not in a pretty way.

因为您在更新的钩子中获得了值,所以可能就是这种情况.

Since you get values in updated hook probably this could be the case.

这篇关于vue js 2:在挂载函数中访问道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆