学习vue的传值心得,刚入门vue,大佬勿喷,请多多指教。
1.父组件传值子组件
父组件嵌套子组件式,在标签里绑定
子组件用props属性接收
例:
<oneproduct :obj='item' :count='0'></oneproduct>// 父组件传值,:为缩写,等同于v-bind:obj='item'
props: ['obj', 'count']// 子组件接收传值,可直接使用,但是推荐在下方重新赋值给新变量再使用
2.子组件传值父组件
子组件用this.$emit传值给父组件
父组件在标签里绑定接收
例:
this.$emit('changeNumberEvent', this.operator); // 子组件传值给父组件(提交),changeNumberEvent为父组件自定义的事件名称,后者为传参数
<myinputBtn @changeNumberEvent='getOperator'> </myinputBtn>; // 父组件接收父组件传值,changeNumberEvent为父组件自定义的事件名称,
getOperator为父组件里的函数
getOperator (op) { // op为子组件传的参数,该处接收
let id = this.goodsItem.id;
if (op === 'plus') {}
3.非父子组件
非父子组件使用vuex的store较好。可传字符串,数组,对象等等。
this.$store.state.cartGoods = self.innerHTML;// 此处为赋值
this.$store.commit('reduceGoods', id); // 此处为提交,让store里的reduceGoods函数启动,后者为参数