1.父组件向子组件传递数据通过props;
2.子组件传递父组件数据需要通过自定义事件;
$emit("定义事件",数据);
父组件:
<!-- 模版 -->
<template>
<!-- 只能存在一个根容器-->
<div class="main"><p style="font-weight:bold;">learn vues</p>
<!-- <forma /> -->
1<input type="text" v-model="parentTexts">1
<forma title="form text" :title1="title1" :parentTexts="parentTexts" @sendinfo="sendsonmsg"/>
<button type="button" >向父级传递数据</button>
<div class="" :style="{'height':'100px'}">{{msgss}}</div>
</div>
</template>
<script>
import forma from './forma'
export default{
name:"learn", //组件名称
components:{forma}, //注入
//所以初始化状态放在data中
data(){
return{
title1:{
name:"对象1"
},
msgss:"",
parentTexts:""
}
},
methods:{
sendsonmsg(data){
this.msgss=data
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="css" scoped>
.main{background-color:red;color:#fff;}
</style>
子组件:
<template>
<div :class="classdemo">
<h1>{{title1.name}}</h1>
<form action="">
<input type="text" value="1232222" v-model="msgtexts" placeholder="请输入手机号">
<p>{{msgtexts}}</p>
<input type="checkbox" id="checkbox" v-model="checked">
<label for="checkbox">{{checked}}</label>
<!-- 懒惰-->
<input type="text" id="" v-model.lazy="msgstxts">
<p>{{msgstxts}}</p>
<!-- number-->
<input type="text" id="" v-model.number="tels">
<p>{{tels}}</p>
<!-- trim-->
<input type="text" id="" v-model.trim="msg">
<p>{{msg}}</p>
<button class="" @click="ageadd">改变按钮来改变p的内容</button>
<p>{{myage}}</p>
{{title}}
{{parentTexts}}
<input type="text" v-model="searchText">111
<div class="btns" @click="sendmsg">子组件向父组件传递数据</div>
</form>
</div>
</template>
<script>
export default {
name: "forma",
data() {
return {
classdemo: "active",
actives: true,
currents: "current",
classobj: {
"text1": true,
"text2": true
},
activeClass: "active1",
currentIndex: "currents",
currentIndex1: "curr",
isActive: true,
colors: "yellow",
msgtexts: "默认值",
checked: false,
msgstxts: "text",
tels: "",
msg: "12345",
myage: 10,
searchText:""
}
},
props: ["title", "title1","parentTexts"],
methods: {
changecss() {
this.classobj = {
"text1": true,
"text2": false
}
},
ageadd() {
this.myage++;
},
sendmsg() {
//this.$emit("sendinfo", "哈哈,我是子组件的数据");
this.$emit("sendinfo",this.searchText);
}
},
watch: {
msgstxts(data) {
if (data == "10") {
console.log("10000");
this.msgstxts = "输入正确"
} else {
}
},
myage(data) {
console.log(data)
}
}
}
</script>
<style scoped>
.active1 {
color: red;
}
.currents {
color: blue;
}
.btns {
200px;
height: 30px;
line-height: 30px;
color: #fff;
background-color: blue;
margin: 0 auto;
}
</style>