<!DOCTYPE?html>
<html?lang="en">
<head>
??<meta?charset="UTF-8">
??<meta?name="viewport"?content="width=device-width,?initial-scale=1.0">
??<title>Document</title>
</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"?:value="dnumber1"?@input="num1input">
??????<h2>props:{{number2}}</h2>
??????<h2>data:{{dnumber2}}</h2>
??????<!--?<input?type="text"?v-model="dnumber2">?-->
??????<input?type="text"?:value="dnumber2"?@input="num2input">
????</div>
??</template>
<script?src="../../js/vue.js"></script>
<script>
??const?app?=?new?Vue({
????el:?'#app',
????data:?{
?????num1:?1,
?????num2:?0
????},
????methods:?{
??????//?子傳父的定義操作
??????num1change(value)?{
????????//?類型轉(zhuǎn)為float類型
????????this.num1?=?parseFloat(value)
??????},
??????num2change(value)?{
????????this.num2?=?parseFloat(value)
??????}
????},
????components:?{
??????cpn:{
????????template:?'#cpn',
????????props:?{
??????????//?不可以直接使用props內(nèi)的數(shù)據(jù)來修改子組件的內(nèi)容,Vue推薦使用其連接父組件实胸,所以需要用data內(nèi)屬性來賦值來進(jìn)行雙向綁定的連接(父傳子)
??????????number1:?Number,
??????????number2:?Number,
????????},
????????data()?{
??????????return?{
????????????dnumber1:?this.number1,
????????????dnumber2:?this.number2
??????????}
????????},
????????methods:?{
??????????num1input(event)?{
????????????//?需求一:表單與頁面數(shù)據(jù)進(jìn)行雙向綁定,event.target.value獲取當(dāng)前的表單值
????????????this.dnumber1?=?event.target.value,
????????????//?需求二:使父組件中的num1,num2也進(jìn)行修改(子傳父)
????????????this.$emit('num1change',?this.dnumber1),
????????????//?需求三:表單一數(shù)據(jù)是表單二的100倍
????????????this.dnumber2?=?this.dnumber1?*?100,
????????????this.$emit('num2change',?this.dnumber2)
??????????},
??????????num2input(event)?{
????????????this.dnumber2?=??event.target.value,
????????????this.$emit('num2change',?this.dnumber2),
????????????this.dnumber1?=?this.dnumber2?/?100,
????????????this.$emit('num1change',?this.dnumber1)
??????????}
????????},
??????}
????},
??})
</script>
</body>
</html>
父傳子步驟:
1.在子組件使用props定義數(shù)據(jù)踩麦。
2.在使用父組件時(shí)使用v-bind給數(shù)據(jù)賦值宝磨。
子傳父步驟:
1.在子組件函數(shù)內(nèi)使用this.$emit()方法發(fā)射數(shù)據(jù)唱捣。
2.在父組件定義發(fā)送過來的函數(shù)及使用其數(shù)據(jù)。