前端 - vue 如何在组件中去处理实例传入的data
本文介绍了前端 - 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
}
});
解决方案
另一个方案是在 prop 里通过 对象 传递数据给子组件,然后在子组件中修改对象的属性。举例如下:
<child prop-a="obj"></child>
父组件中的 data
data () {
return {
obj: {
a: 1,
b: 2
}
}
}
然后就可以在子组件中通过 this.propA.a = 100 来修改数据了。
这篇关于前端 - vue 如何在组件中去处理实例传入的data的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文