【问题标题】:VueJS - how component gets global data item?VueJS - 组件如何获取全局数据项?
【发布时间】:2016-07-11 05:32:15
【问题描述】:

我有这样的代码:

Vue.component("sample", {
    inherit: true,
    template: "#sample",
    props: {
       active : "active",
       ...
    },
    methods: {
      forceChangeActive: function(){
         var activeItem = this.$parent._data.active;
         var modalSetup = this.$parent._data.showModal;
         console.log("1.before function", this.$parent._data);
         this.$parent.$options.methods.baseAction(activeItem, modalSetup);
         console.log("2.before function", this.$parent._data);
      });
    }
});
new Vue({
    el: "#app",
    data: {
        active: 0,
        showModal: false,
        ...
    }, 
    methods: {
        baseAction: function(activeItem, modalSetup){
            console.log("3.modal", modalSetup, "activeItem": activeItem);
            modalSetup = true;
            activeItem = 2;
            console.log("4.modal", modalSetup, "activeItem": activeItem);
        }
    }
});

在新的 Vue 中有 active 和 showModal 数据变量。现在,如果我使用 this.active 或 this.showModal,我对两者都没有定义。 控制台输出为:

  1. 函数对象之前 { active=0, showModal=false }
  2. 模态错误,activeItem 0
  3. 模态真,activeItem 2
  4. 函数对象之前 { active=0, showModal=false }

如何在新的 Vue 或组件中更改变量的值?

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    inherit:true 已弃用。

    您需要使用属性将activeshowModal 显式传递给子组件。您可以使用.sync 来确保它们也被共享回父级:

    <sample :active.sync="active" :show-modal.sync="showModal"></sample>
    

    【讨论】:

      猜你喜欢
      • 2017-07-29
      • 1970-01-01
      • 2017-08-28
      • 2022-07-22
      • 2020-03-16
      • 1970-01-01
      • 2019-08-02
      • 1970-01-01
      • 2018-02-19
      相关资源
      最近更新 更多