作业需求
- 需求1:定义两个输入框,通过输入框输输入的值改变页面显示的值
- 需求2:改变第一个输入框的值的同时使得第二个输入框的值变为100倍并显示
- 需求3:改变第二个输入框的值的同时使得第一个输入框的值变为1/100并显示
- 用watch实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="xiaonaihu" />
<meta name="generator" content="HBuilder X" />
<title>父子组件的案例watch实现</title>
<script src="../../lib/vue.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
<cpn :number1 = "num1"
:number2 = "num2"
@num1change = "num1change"
@num2change = "num2change"></cpn>
</div>
<template id="cpn">
<div>
<h2>props:{{number1}}</h2>
<h2>data:{{dnumber1}}</h2>
<input type="text" v-model="dnumber1">
<!-- <input type="text" v-bind:value = "dnumber1" v-on:input = "dnumber1=$event.target.value"> -->
<!-- <input type="text" v-bind:value = "dnumber1" v-on:input = "num1Input"> -->
<h2>props:{{number2}}</h2>
<h2>data:{{dnumber2}}</h2>
<input type="text" v-model="dnumber2">
<!-- <input type="text" :value = "dnumber2" @input = "dnumber2=$event.target.value"> -->
<!-- <input type="text" :value = "dnumber2" @input = "num2Input"> -->
</div>
</template>
<script type="text/javascript">
var app = new Vue({
el: "#app",
data:{
num1:1,
num2:0
},
methods: {
num1change(value) {
console.log(typeof value);//String类型
// this.num1 = value;
//方法1:乘一个数值直接转换
this.num1 = value * 1;
// 方法2:parseInt()函数转换
// this.num1 = parseInt(value);
this.num1 = parseFloat(value);
},
num2change(value) {
console.log(typeof value);//String类型
// this.num2 = value;
//方法1:乘一个数值直接转换
this.num2 = value * 1;
// 方法2:parseInt()函数转换
// this.num2 = parseInt(value);
this.num2 = parseFloat(value);
}
},
components: {
cpn:{
template:"#cpn",
props: {
// 如果直接展示内容可以直接绑定
number1:Number,
number2:Number
},
// 如果需要修改,建议使用data
data() {
return ({
dnumber1:this.number1,
dnumber2:this.number2
})
},
watch: {
dnumber1(newValue) {
this.dnumber2 = newValue * 100;
this.$emit('num1change',newValue);
},
dnumber2(newValue) {
this.dnumber1 = newValue / 100;
this.$emit('num2change',newValue);
}
}
}
}
});
</script>
</body>
</html>