目前刚刚开始学习vue,编写了一个小组件,但是这个组件再一个地方可以用,但是再其他地方会发生赋值错误
var num = {
props: ['index', 'num', 'min', 'max', 'step'],
template: '<div><span class="jia" @click="change(-1,min,max)">-</span>\n' +
'<input class="num" v-model="count" :value="count">\n' +
'<span class="jian" @click="change(1,min,max)">+</span></div>',
data: function () {
return {
count: this.num,
cindex: this.index,
}
},
methods: {
change: function (type, min, max) {
var num1 = this.count + type * this.step;
if (num1 >= min && num1 <= max) {
this.count = num1;
this.$emit('change', [this.index, num1]);
}
},
}
};
其中正确的地方我是这么调用的
<num :index="index" v-on:change="change" :num="item.num" :min="item.minimum" :max="item.goods_stock" step=1></num>
运行截图
错误的地方
<num v-on:change="change" :index="1" :num="goodsInfo.minimum" :min="goodsInfo.minimum" :max="goodsInfo.goods_stock" step=1></num>
其中index因为没有直接赋值一个固定的数
运行截图
这是为啥了,一个可以成功赋值,另一个就不行
在你的方法中,你对data中的属性执行了赋值操作,这是不对的。
vue提倡的是单项数据流,虽然你可以强制修改组件里的data中的各个属性值,但是会提示你的,也是不提倡的,想要操作data中的属性值,应该使用计算属性computed,把data中的属性值赋值给computed中的值。
你需要在你的组件中加入computed属性去存储需要赋值的属性。