子组件向父组件传递数据
本质:父组件向子组件传递方法,子组件调用这个方法同时把 数据当作参数 传递给父组件
:父组件
<numbox @getcount="getSelectedCount" ></numbox>
data(){
return {
selectCount:1,//保存用户选中的商品的数量,默认为1
}
},
methods:{
getSelectedCount(count){//这是父组件的方法,向子组件传递
//当子组件把 选中的数量传递给父组件的时候,把 选中的值保存到 selectCount 上
this.selectCount=count;
//console.log(this.selectCount);
}
}
:子组件
<input
id="test"
class="mui-input-numbox"
type="number"
value="1"
@change="countChanged"
ref="numbox"
/>
countChanged() {
//绑定了@change事件每当 文本框的数据被修改时 立即把调用 countChanged方法
//把最新的数据,通过事件调用,传递给父组件
// 子组件向父组件传递参数 $emit('父组件绑定的属性名',子组件要向父组件传递的值);
this.$emit("getcount", parseInt(this.$refs.numbox.value));
}
父组件向子组件传递数据
本质:父组件中绑定属性,子组件用 props: [“属性名”]接受
:父组件
<numbox v-bind:max="goodsinfo.stock_quantity" ></numbox>
<!--绑定了 max 属性,将goodsinfo.stock_quantity的值传递给子组件-->
:子组件
<div class="mui-numbox" data-numbox-min="1" :data-numbox-max="max">
<!--由v-bind:data-number-max来接受父组件传来的值-->
props: ["max"],//子组件接受来自父组件绑定的属性名
//如果父组件传递的值,是异步操作的结果,那么子组件获得的值为undefined
//解决:使用 watch 属性监听,来监听 父组件传递过来的 max 值,
//不管 watch 会被触发几次,但是最后一次,肯定是一个 合法的 max 数值
watch: {
//属性监听
max: function(newVal, oldVal) {
//在MUI文档中查找 使用 JS API 设置 numbox 的最大值
mui(".mui-numbox")
.numbox()
.setOption("max", newVal);
}
}