vue 如何在组件中去处理实例传入的data

vue新手求助:
全局注册了组件,在vue实例里通过props将实例的data传给组件,这样可以在组件中获取到data,但是,我在组件的methods中去对props操作就会报错了:

代码也是从网上找的,自己想改一下,但是改出问题了……

Vue.component("page", {
        template: "#page",
        props: {
            current: {
                type: Number,
                default: 1
            },
            showItem: {
                type: Number,
                default: 5
            },
            allpage: {
                type: Number
            }
        },
        computed: {
            pages: function() {
                var pag = [];
                if (this.current < this.showItem) { //如果当前的激活的项 小于要显示的条数
                    //总页数和要显示的条数那个大就显示多少条
                    var i = Math.min(this.showItem, this.allpage);
                    while (i) {
                        pag.unshift(i--);
                    }
                } else { //当前页数大于显示页数了
                    var middle = this.current - Math.floor(this.showItem / 2), //从哪里开始
                        i = this.showItem;
                    if (middle > (this.allpage - this.showItem)) {
                        middle = (this.allpage - this.showItem) + 1
                    }
                    while (i--) {
                        pag.push(middle++);
                    }
                }
                return pag
            }
        },
        methods: {
            goto: function(index) {
                if (index == this.current) return;
                //问题应该就在这里,改动了props current的值
                this.current = index;
                
                console.log(this.current);
            }
        }
    });

    var page = new Vue({
            el: '#paginationWrap',
            data: {
            current: 1,
            showItem: 5,
            allpage: 13
        }
    });
回复
阅读 6.1k
3 个回答

另一个方案是在 prop 里通过 对象 传递数据给子组件,然后在子组件中修改对象的属性。举例如下:

<child prop-a="obj"></child>

父组件中的 data

data () {
  return {
    obj: {
      a: 1,
      b: 2
    }
  }
}

然后就可以在子组件中通过 this.propA.a = 100 来修改数据了。

因为props是单项流动的,所以子组件不能修改父组件传入的props;父组件传入的props应该交给父组件修改,这里可以通过emit事件来做。Vue中提倡单向的数据流动,数据从上往下传递,子组件不能修改父组件的数据。
文档中写的很明白,建议多看几遍文档:单向数据流

新手上路,请多包涵

props是不能改的,新定义一个data


        props: {
            current: {
                type: Number,
                default: 1
            }
            ...
        },
        data: function() {
          return {
              currentIndex: this.current
          }
        },
        methods: {
            goto: function(index) {
                if (index == this.currentIndex) return;
                //问题应该就在这里,改动了props current的值
                this.currentIndex = index;
                
                console.log(this.currentIndex);
            }
        }
        
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏