组件之间的传值
注意: 仔细看代码中的注释,不要遗漏细节, 然后模仿自己写出来。废话不多说,上干货。
一. prop传值(父--->子)
注意:
- 子组件使用props来声明需要从父组件接受的数据
- 如需改变data的值,触发操作,通过ref加方法来获取子组件数据
代码展示:
//父组件
<template>
<div>
<HelloWorld ref="helloWorld" :message1="messageToHelloWorld"></HelloWorld>
<el-button type="primary" @click="submitForm()">保存</el-button>
<div/>
<template/>
<script>
import HelloWorld from './components/HelloWorld'
export default {
components: {
HelloWorld
},
name: 'App',
data() {
return {
messageToHelloWorld:'我是父组件向下传递的信息'
}
},
method(){
//通过ref加方法来获取子组件数据
submitForm(){
this.$refs.helloWorld.getFormData();
}
}
}
</script>
//子组件
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<h2>Essential Linkssss</h2>
<h3>{{ message1 }}</h3>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
props: ['message1'],
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
}
method(){
// 获取子组件的数据
getFormData(){
return this.form; //返回的数据
},
},
}
</script>
还需注意
prop验证:
Vue.component('my-component',{
props:{
//必须是数字类型
propA:Number
//必须是字符串或数字类型
propB:[String,number]
//布尔值,如果没有定义,默认值是true
propC:{
type:Boolean,
default:true
},
//数字,而且是必传
propD:{
type:Number,
required:true
},
//如果是数组或对象,默认值必须是一个函数来返回
propE:{
type:Array,
default:function(){
return [];
}
},
//自定义一个验证函数
propF:{
validator:function (value){
return value>10
}
}
}
});
二. 子组件向父组件传值(子--->父)
//父组件:
<template>
<div>
<span>{{name}}</span>
<br>
<br>
<child @childByValue="parentByValue"></child>
</div>
</template>
<script>
import child from './child'
export default {
components: {
child
},
data () {
return {
name: ''
}
},
methods: {
parentByValue: function (childValue) {
// childValue就是子组件传过来的值
this.name = childValue
}
}
}
</script>
// 子组件:
<template>
<div>
<span>{{childValue}}</span>
<!-- 定义一个子组件传值的方法 -->
<input type="button" value="点击触发" @click="childClick">
</div>
</template>
<script>
export default {
data () {
return {
childValue: '我是子组件的数据'
}
},
methods: {
childClick () {
// childByValue是在父组件监听的方法
// 第二个参数this.childValue是需要传的值
this.$emit('childByValue', this.childValue)
}
}
}
</script>
三. 非父子组件进行传值
注意:非父子组件之间传值,需要定义个公共的公共实例文件bus.js,作为中间仓库来传值,不然路由组件之间达不到传值的效果。
//公共bus.js
import Vue from 'vue'
export default new Vue()
// A组件:
<template>
<div>
<span>{{elementValue}}</span>
<input type="button" value="点击触发" @click="elementByValue">
</div>
</template>
<script>
// 引入公共的bug,来做为中间传达的工具
import Bus from './bus.js'
export default {
data () {
return {
elementValue: 4
}
},
methods: {
elementByValue: function () {
Bus.$emit('val', this.elementValue)
}
}
}
</script>
//B组件:
<template>
<div>
<input type="button" value="点击触发" @click="getData">
<span>{{name}}</span>
</div>
</template>
<script>
import Bus from './bus.js'
export default {
data () {
return {
name: 0
}
},
mounted: function () {
var vm = this
// 用$on事件来接收参数
Bus.$on('val', (data) => {
console.log(data)
vm.name = data
})
},
methods: {
getData: function () {
this.name++
}
}
}
</script>
转载请注明出处:http://www.nali5.com/article/20230513/716535.html