(1)this.$emit()
子组件通过this.$emit()
的方式将值传递给父组件,这里的func是父组件中绑定的函数名
子组件
<template>
<div class="son">
<!-- 按钮 -->
<input type="btton" @click="sendMsg" value="给父组件传值">
</div>
</template>
<script>
export default {
data(){
return{
msg:'我是子组件的msg'
}
},
methods:{
sendMsg(){
this.$emit('func',this.msg); //func:是父组件指定的传数据绑定的参数,this.msg:子组件给父组件传递的参数
}
}
}
</script>
<style lang="less" scoped>
.son{
input{
width: 100px;
height: 37px;
font-size: 15px;
border-radius: 3px;
border-style: none;
border: 1px solid #ededed;
margin: 60px;
padding-left: 10px;
&:hover{
background: #ededed;
cursor: pointer;
}
}
}
</style>
父组件
<template>
<div id="app">
<son @func='getMsg'></son>
<!-- 点击按钮,p中的值为子组件传过来的值 -->
<p v-text="this.msgFormSon"></p>
</div>
</template>
<script>
import son from './components/son.vue'
export default {
name: 'app',
components: {
son
},
data(){
return{
msgFormSon:'this is msg'
}
},
methods:{
getMsg(data){ //参数为子组件传递过来的数据
this.msgFormSon = data;
console.log(this.msgFormSon)
}
}
}
</script>
(2)this.$parent
可以访问到父组件上所有的 data(){ }里的数据信息和生命周期方法,methods里的方法
子组件
<template>
<div v-if="visible">
<p>{{header}}</p>
我是子组件:{{num}}
</div>
</template>
<script>
export default {
components: {
},
props: { //父组件给子组件传值
header:{
type:String,
required:false,
default:''
}
},
data(){
return {
num:'',
visible:false
}
},
mounted(){
this.$parent.message = new Date()
},
methods:{
add(){
this.visible = true
}
}
};
</script>
父组件
<template>
<div id="app">
<example ref="example" :header="header"></example>
子组件给父组件传值:{{message}}
<a-button @click="open">子组件</a-button>
</div>
</template>
<script>
import example from '@/components/example'
export default {
components:{
example
},
mounted(){
this.$refs.example.num = 222
},
data() {
return {
header:'我是父组件给子组件传的值',
message:''
}
},
created(){
},
directives:{
background:{
inserted(el){
el.style.background='yellow'
}
}
},
methods: {
open(){
this.$refs.example.add()
}
}
}
</script>
<style>
#app{
padding: 15px;
}
.container{
padding: 30px;
height: 800px;
}
</style>
(3)this.$refs
ref 有三种用法:
1、ref 加在普通的元素上,用this.ref.name 获取到的是dom元素
2、ref 加在子组件上,用this.ref.name 获取到的是组件实例,可以使用组件的所有方法并且可以传值给子组件
3、如何利用 v-for 和 ref 获取一组数组或者dom 节点
子组件
<template>
<div v-if="visible">
我是子组件:{{num}}
</div>
</template>
<script>
export default {
data(){
return {
num:'',
visible:false
}
},
methods:{
add(){
this.visible = true
}
}
};
</script>
父组件
<template>
<div id="app">
<example ref="example"></example>
<a-button @click="open">子组件</a-button>
</div>
</template>
<script>
import example from '@/components/example'
export default {
components:{
example
},
mounted(){
this.$refs.example.num = 222 //传值给子组件
},
data() {
return {
},
methods: {
open(){
this.$refs.example.add() //调用子组件中方法
}
}
}
</script>