vue组件传值在日常开发中比较常见。
一般有三种传值方式:1.父传子、2.子传父、3.兄弟组件之间通信
父子组件传值
父组件代码如图下:
<template>
<div>
//第三步声明子组件
//父组件传值需要用':'来动态传值
//父组件接收值需要用'@'
<child :list="list" @getlist="getlist"></child>
</div>
</template>
<script>
//第一步引入子组件
import child from "./child";
export default {
data() {
return {
list: "你好啊",
};
},
//第二步注册子组件
components: {
child,
},
methods: {
//接收子组件传来的值并且赋值给list
getlist(val) {
this.list = val;
},
},
};
</script>
子组件如图下:
<template>
<div>
<button @click="btn">{{ list }}</button>
</div>
</template>
<script>
export default {
//使用props接收父组件的值
props: ["list"],
data() {
return {};
},
methods: {
//使用点击事件来触发,子组件像父组件传值
//使用this.$emit(属性名,属性值)
btn() {
this.$emit("getlist",'hello world')
},
},
};
</script>
以上就是父子组件传值,需要注意的是父组件要记住三步:1、引入2、注册3、声明。父组件传值使用':'来动态传值,【:list="list"】前面是属性名后面是属性值
子组件需要注意的是使用props来接收父组件传来的值,props后面跟'[]'是不限制类型,跟'{}'需要加上值的数据类型,否则会报错。子组件传值使用:this.$emit('属性名','属性值'),父组件接收使用:@属性名='传来的属性名'
非父子组件传值(兄弟传值)
当点击组件1,组件2内容随即改变内容;反之,也是实现这样的功能
方式: 非父子组件中的 兄弟组件之间 如何传递数据,
1、先看一下点击组件本身,在组件本身出现数据变化
<div id="root">
<child content="miya"></child>
<child content="wang"></child>
</div>
<script>
Vue.prototype.bus = new Vue ()
Vue.component('child', {
props: {
content: String
},
template: '<div @click="handleClick">{{content}}</div>',
methods: {
handleClick: function() {
alert(this.content)
}
}
})
var vm = new Vue({
el: "#root"
})
</script>
分别弹出各自的内容
2、再看看如何把数据传递给另一个组件
//div部分同上
<script>
Vue.prototype.bus = new Vue ()
Vue.component('child', {
props: {
content: String
},
template: '<div @click="handleClick">{{content}}</div>',
methods: {
handleClick: function() {
this.bus.$emit('change', this.content) //重点在这里
}
}
})
var vm = new Vue({
el: "#root"
})
</script>
3、向外触发事件之后,其他组件将通过 监听 的方式接收数据方式:借助生命周期钩
//div部分同上
<script>
Vue.prototype.bus = new Vue ()
Vue.component('child', {
props: {
content: String
},
template: '<div @click="handleClick">{{content}}</div>',
methods: {
handleClick: function() {
this.bus.$emit('change', this.content)
}
},
mounted: function(){
this.bus.$on('change', function(msg){ //重点在这里
alert(msg)
})
}
})
var vm = new Vue({
el: "#root"
})
</script>
一个child的组件去触发事件时,两个child组件通过 $on 监听 change 对同一个事件进行事件,监听到该事件后,两个组件都会弹 事件中对组件的触发事件所传递过来的内容 (两组件实际共弹了四次弹窗 )
5、兄弟组件间进行传值 完整代码:
<body>
<div id="root">
<child content="miya"></child>
<child content="wang"></child>
</div>
<script>
Vue.prototype.bus = new Vue ()
Vue.component('child', {
data: function() {
return {
selfContent: this.content
}
}, //重点在这
props: {
content: String
},
template: '<div @click="handleClick">{{selfContent}}</div>',
methods: {
handleClick: function() {
this.bus.$emit('change', this.selfContent)
}
}, //重点在这
mounted: function(){
var this_ = this
this.bus.$on('change', function(msg){
this_.selfContent = msg //重点在这
})
}
})
var vm = new Vue({
el: "#root"
})
</script>
</body>