$emit : 子组件触发父组件方法
ref : 父组件调用子组件方法
现在有父子组件分别如下:
Parent.vue
<template> <div> <span>这里是父组件</span> <Child ref="child" v-bind:parentValue="parent" @editValue="edit"></Child> </div> </template> <script> //引入子组件 import Child from "./Child.vue" export default { //包含子组件 components:{Child}, data(){ return{ parent:"父组件的值" } }, methods:{ edit(msg){ this.parent=msg; } } } </script>
Child.vue
<template> <div> <span>这里是子组件</span> <span>父组件传的值:{{this.parentValue}}</span> <button @click="editParentValue">反向修改父组件的值</button> </div> </template> <script> export default { //父组件给子组件传值使用的是props关键字 //这里声明父组件传值的类型是String props:{ parentValue:String }, methods:{ editParentValue(){ //子组件触发父组件函数用$emit //里面的两个参数分别是函数名称和改动的值 this.$emit("editValue","子组件改值"); } } } </script>
在上面的传值中,父子组件使用公共的变量parentValue,父组件组件使用的是v-bind,子组件使用的是props.一个给定了值,一个指定了类型。
子组件使用$emit来触发公共函数editValue,父组件使用v-on来监听
另外,由于在父组件中使用ref来为子组件做了标记,那么可以用
this.$refs.child.XXX()
来调用子组件里面的方法。
关于ref
ref可以减少获取Dom节点的消耗。
我们获取值得一般方法是
document.querySelector(".input")
获取节点然后获取值。
而声明了ref不需要再获取Dom节点。
一个页面可以有多个ref,所以是this.$refs加声明的名称