php网站开发教程下载,四川省建设厅建筑业信息网,vue做响应式网站,贵阳网站建设王道下拉惠$refs 的使用方法就是在元素或组件标签上添加ref属性指定一个引用信息#xff0c;引用信息将会注册在父组件的$refs对象上#xff0c;在js中使用$refs来指向DOM元素或组件实例#xff1b; 应用一#xff1a;在DOM元素上使用$refs可以迅速进行dom定位#xff0c;类似于$(引用信息将会注册在父组件的$refs对象上在js中使用$refs来指向DOM元素或组件实例 应用一在DOM元素上使用$refs可以迅速进行dom定位类似于$(selectId)如下
templatediv classparentp reftestTxt{{oldMsg}}/pbutton clickchangeMsg()点击修改段落内容/button/div/templatescriptexport default {data(){return {oldMsg:这是原有段落数据内容,newMsg:hello,这是新的段落数据内容,}},methods:{changeMsg(){this.$refs.testTxt.innerHTMLthis.newMsg;},}}/script 应用二也能在组件上使用ref属性可以通过$refs实现对子组件操作,如下
①使用this.$refs.paramsName能更快的获取操作子组件属性值或函数
parentone.vue 如下
templatediv classparentChildone refchildItemId/Childonep stylecolor:blue;{{msgFromChild}}/pbutton clickgetChildMsg()使用$refs获取子组件的数据/button/div
/templatescript
import Childone from ./childone
export default {components:{Childone},data(){return {msgFromChild:,}},methods:{getChildMsg(){this.msgFromChildthis.$refs.childItemId.childMsg;},}
}
/script
childone.vue 如下
templatediv classchild/div
/templatescript
export default {data(){return {childMsg:这是子组件的参数}}
}
/script 扩展到$parent 、$children的使用
②我们可以使用$children[i].paramsName 来获取某个子组件的属性值或函数$children返回的是一个子组件数组
这里就只写父组件的代码了parentone.vue如下
templatediv classparentChildone/ChildoneChildtwo/Childtwop stylecolor:blue;{{msgFromChild}}/pbutton clickgetChildMsg()使用$children来获取子组件的数据/button/div
/templatescript
import Childone from ./childone
import Childtwo from ./childtwo
export default {components:{Childone,Childtwo},data(){return {msgFromChild:,}},methods:{getChildMsg(){this.msgFromChildthis.$children[1].child2Msg;},}
}
/script ③那么子组件怎么获取修改父组件的数据内容这需要使用$parent
parentone.vue如下
templatediv classparentChildone/Childone/div
/templatescript
import Childone from ./childone
export default {components:{Childone},data(){return {parentMsg:这是父组件的数据,}}
}
/script
childone.vue如下
templatediv classchildp stylecolor:red;{{msgFromParent}}/pbutton clickgetParentMsg()点击使用$refs获取父组件的数据/button/div
/templatescript
export default {data(){return {msgFromParent:}},methods:{getParentMsg(){this.$parent.parentMsg子组件中可以修改父组件的内容这是通过子组件修改所得this.msgFromParentthis.$parent.parentMsg;}}
}
/script 注意
· 当使用v-for的元素或组件引用信息$refs将是包含DOM节点的或组件实例的数组类似$children的使用
· 注意 $refs不能在created生命周期中使用 因为在组件创建时候 该ref还没有绑定元素 created(){//报错 $refs不能在created生命周期中使用 因为在组件创建时候 该ref还没有绑定元素this.changeMsg(); },methods:{changeMsg(){this.$refs.testTxt.innerHTMLthis.newMsg;},}
· 它是非响应的所以应该避免在模板或计算属性中使用 $refs ,它仅仅是一个直接操作子组件的应急方案