vue组件遇到了问题

目前刚刚开始学习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>

运行截图

clipboard.png

错误的地方

<num  v-on:change="change" :index="1" :num="goodsInfo.minimum" :min="goodsInfo.minimum" :max="goodsInfo.goods_stock" step=1></num>

其中index因为没有直接赋值一个固定的数
运行截图

clipboard.png

这是为啥了,一个可以成功赋值,另一个就不行

阅读 3.1k
3 个回答

在你的方法中,你对data中的属性执行了赋值操作,这是不对的。

vue提倡的是单项数据流,虽然你可以强制修改组件里的data中的各个属性值,但是会提示你的,也是不提倡的,想要操作data中的属性值,应该使用计算属性computed,把data中的属性值赋值给computed中的值。

你需要在你的组件中加入computed属性去存储需要赋值的属性。

已解决再vue组件里面添加一个watch就好了
最后的代码

var num = {
    props: {
        index:Number,
        num:{type:Number,require:true},
        min:{type:Number,default:1},
        max:{type:Number,require:true},
        step:{type:Number,default:1}
        },
    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 () {
        console.log(this.num);
        return {
            count: this.num,
            cindex: this.index,
        }
    },
    watch:{
      num:function (cur, old) {
          this.count=cur;
      }
    },
    methods: {
        change: function (type, min, max) {
            if (this.count=== undefined){
                this.count=this.num;
            }
            var num1 = this.count + type * this.step;
            if (num1 >= min && num1 <= max) {
                this.count = num1;
                this.$emit('change', [this.index, num1]);
            }
        },
    }
};

但是为啥一个能用一个不能用还是不清楚

新手上路,请多包涵
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题