Vue父子组件模块参数传值的几种方法
[ 2022-05-07 21:21:20 | 作者: admin ]
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">
<script>
export default {
data () {
return {
childValue: '我是子组件的数据'
}
},
methods: {
childClick () {
this.$emit('childByValue', this.childValue)
}
}
}
</script>父组件:
<!-- 引入子组件 定义一个on的方法监听子组件的状态-->
<child v-on:childByValue="childByValue"></child>
<script>
methods: {
childByValue: function (childValue) {
// childValue就是子组件传过来的值
this.name = childValue
}
}
}
</script>3.父组件调用子组件的方法通过ref
在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>那么子组件怎么获取修改父组件的数据内容?这需要使用$parent


原文链接:https://blog.csdn.net/lianwenxiu/article/details/87898688
[最后修改由 admin, 于 2022-05-07 22:31:49]
评论Feed: http://blog.xg98.com/feed.asp?q=comment&id=2855
这篇日志没有评论。
此日志不可发表评论。







