<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="/js/vue.js"></script>
</head>
<body>
<h3>需求: 1、data数据和props数据都要和输入框双向绑定 2、第一个输入框是第二个的100倍 3、第二个输入框是第一个1/100</h3>
<div id="app">
<child :pnum1='num1' :pnum2='num2' @num1change='num1change' @num2change='num2change'></child>
</div>
<template id="temp">
<div>
<h2>dnum1:{{dnum1}}</h2>
<h2>pnum1:{{pnum1}}</h2>
<!-- <input type="text" v-model="dnum1"> -->
<!-- v-model='dnum1' 等价于 :value='dnum1' @input='$event.target.value' -->
<input type="text" :value='dnum1' @input='num1Input'>
<h2>dnum2:{{dnum2}}</h2>
<h2>pnum2:{{pnum2}}</h2>
<!-- <input type="text" v-model='dnum2' > -->
<input type="text" :value='dnum2' @input='num2Input'>
</div>
</template>
<script>
new Vue({
el: '#app',
data: {
num1: 0,
num2: 1
},
methods: {
num1change(value) {
// 需要转为数字类型
this.num1 = parseFloat(value)
},
num2change(value) {
this.num2 = parseFloat(value)
}
},
components: {
child: {
template: '#temp',
props: {
// 定义类型
pnum1: Number,
pnum2: Number
},
data() {
return {
dnum1: this.pnum1,
dnum2: this.pnum2
}
},
methods: {
num1Input(event) {
// 1、将input中的value赋值到dnum1
this.dnum1 = event.target.value
// 2、为了让父组件可以修改值,发出一个事件
this.$emit('num1change', this.dnum1)
// 3、同时修改dnum2的值
this.dnum2 = this.dnum1 * 100
this.$emit('num2change', this.dnum2)
},
num2Input(event) {
this.dnum2 = event.target.value
this.$emit('num2change', this.dnum2)
this.dnum1 = this.dnum2 / 100
this.$emit('num1change', this.dnum1)
}
}
}
}
})
</script>
</body>
</html>
网友评论