<h1 id="一组件">一、组件
<h3 id="父组件传递数据到子组件">1、父组件传递数据到子组件
<h4 id="props第一种写法">01、props第一种写法
Vue.component("my-component",{
props: ['msg'],template: "child component,{{msg}}"
})
Vue.component("my-component",{
props: {
msg:{
required:true/false //代表改变是否必须
type:String/Array/Number/Object //传入的变量的类型检查
},names:{
required:false,type:Array
}
},{{msg}}"
})
//使用组件
<template id="child">
子组件标题
//先注册组件再使用组件
Vue.component("child-component",{
template: "#child",methods: {
send() {
//子组件向父组件传递数据的方式,是通过事件触发
this.$emit("myevent","green")
//myevent---->子组件向父组件发送的事件名称
//green----->是发送的数据
}
}
})
//创建vue实例
new Vue({
el: ".box",data: {
bgColor: 'red'
},methods: {
handle(data) {
this.bgColor = data
}
}
})</code></pre>
<h3 id="非父子组件的通信">3、非父子组件的通信
<h4 id="解决方案通过中间桥梁实现非父子组件之间的通信">01、解决方案:通过中间桥梁实现非父子组件之间的通信
<h4 id="实现过程">02、实现过程
//创建一个非父子组件之间通信的中间桥梁
var hub = new Vue()
//第一个组件
Vue.component("first-component",{
template:" <button @click='send'>发送事件 ",methods:{
send(){
//通过中间hub发送事件
hub.$emit("tosecond","some data....")
}
})
//第二个组件
Vue.component("first-component",created:function(){
//通过hub监听事件
hub.$on("tosecond",function(data){
//data---->hub发送事件是所携带的参数
})
}
})

{{title}}
{{title}}
script样式
//定义一个评分的组件
Vue.component("Star",{
template:"#star",data:function(){
return {
titles:["总 评","推 荐","口味包装"]
}
},props:{
stars:{
required:true,type:Array
}
},created:function(){
console.log(this.stars)
}
})
new Vue({
el: ".container",data:{
products:[{
img: "img/01.jpg",title: "商品1",stars: [2,2,5]
},{
img: "img/02.jpg",title: "商品2",stars: [3,4,4]
},{
img: "img/03.jpg",title: "商品3",3,3]
},{
img: "img/04.jpg",title: "商品4",1,4]
}]
}
})
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|