1.父向子传值props
父组件:
<child :inputName="name">
子组件:
1. props: {
inputName: String,
required: true
}
2. props: ["inputName"]
2.子组件向父组件传值$emit
子组件:
<span>{{childValue}}</span>
<!-- 定义一个子组件传值的方法 -->
<input type="button" value="点击触发" @click="childClick">
export default {
data () {
return {
childValue: '我是子组件的数据'
}
},
methods: {
childClick () {
this.$emit('childByValue', this.childValue)
}
}
}
父组件
<!-- 引入子组件 定义一个on的方法监听子组件的状态-->
<child v-on:childByValue="childByValue"></child>
methods: {
childByValue: function (childValue) {
// childValue就是子组件传过来的值
this.name = childValue
}
}
}
3.父组件调用子组件的方法通过ref
在DOM元素上使用 r e f s 可 以 迅 速 进 行 d o m 定 位 , 类 似 于 refs可以迅速进行dom定位,类似于 refs可以迅速进行dom定位,类似于(“selectId”)
使用this.$refs.paramsName能更快的获取操作子组件属性值或函数
子组件:
methods:{
childMethods() {
alert("I am child's methods")
}
}
父组件: 在子组件中加上ref即可通过this.$refs.method调用
<template>
<div @click="parentMethod">
<children ref="c1"></children>
</div>
</template>
<script>
import children from 'components/children/children.vue'
export default {
data(){
return {
}
},
computed: {
},
components: {
'children': children
},
methods:{
parentMethod() {
console.log(this.$refs.c1) //返回的是一个vue对象,可以看到所有添加ref属性的元素
this.$refs.c1.childMethods();
}
},
created(){
}
}
</script>