vue js 2:已安装函数中的访问道具

Epi*_*ist 8 vue.js vue-component vuejs2

我在子组件中有数据道具。在挂载函数的子组件内部,我需要从props中获取特定值并设置select下拉值。我正在使用vue-multiselect插件,它工作正常。这是代码。

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);
//  }
};
Run Code Online (Sandbox Code Playgroud)

现在,只有当我确实获得订阅时,才存在于beforeUpdate和updated函数中,但这在每次更改值时都会调用,而不需要进行此更改。我只需要第一次更改它即可设置下拉初始值。

dil*_*111 15

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

例子 :

<ChildComponent :data="testData" />
Run Code Online (Sandbox Code Playgroud)

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

<ChildComponent v-if="testData" :data="testData" />
Run Code Online (Sandbox Code Playgroud)

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

由于您在更新的挂钩中获得值,因此可能就是这种情况。

  • 从我看来,这是这个问题的最佳答案。 (2认同)

Ara*_*jay 7

我使用@watch 解决了类似的问题。也许这可以工作?

module.exports = {
  props: ["Subscriptions"]

  // this mounted is probably not necessary
  mounted: function () {
    getSubscriptions(this.Subscriptions)
  },  

  watch: {
    Subscriptions: [{
      handler: 'getSubscriptions'
    }]
  },

  methods: {
    getSubscriptions(el) {
      console.log(el);
    }
  }
};
Run Code Online (Sandbox Code Playgroud)


V. *_*bor 6

您为什么要尝试通过“ $ parent”访问当前组件道具?

它应该像这样工作:

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

      Vue.nextTick(function () {
        console.log(vm.Subscriptions);
      });
  },  
  beforeUpdate() {
    console.log(this.Subscriptions);
  },
  updated() {
    console.log(this.Subscriptions);
  }
};
Run Code Online (Sandbox Code Playgroud)

更新:

无论如何,我不知道您是否需要下一个刻度,请尝试使用创建的功能,并且不使用nextTick。

created() {
  alert(this.Subscriptions);
},
Run Code Online (Sandbox Code Playgroud)


小智 6

从道具接收数据:

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

        vm.$nextTick(function () {      
           console.log(vm.Subscriptions);
        });
    },  
Run Code Online (Sandbox Code Playgroud)