子组件向父组件传值,使用属性props
<div id="app">
<msg txt="我是txt"></msg>
</div>
<script src="./libs/vue.js"></script>
<script>
const txt ={
template:`<h1>{{txt}}</h1>`,
props:['txt']
}
var app = new Vue({
el:'#app',
components:{
msg:txt,
}
})
</script>
子组件向父组件传值,子组件派发事件$emit
<div id="app">
<p>子组件传过来的值{{fatherVal}}</p>
<btn @listen="listenHandle"></btn>
</div>
<script src="./libs/vue.js"></script>
<script>
const Button ={
template:`<div>
<input type="text" v-model="msg"/>
<button @click="sendHandle()">给父组件传值</button>
</div>`,
data(){
return{
msg:''
}
},
methods: {
sendHandle(){
this.$emit('listen',this.msg)
console.log(this.msg)
}
},
}
var app = new Vue({
el:'#app',
components:{
btn:Button
},
data:{
fatherVal:'',
},
methods: {
listenHandle(val){
this.fatherVal = val
console.log('监听到了')
}
},
})
</script>
非相关组件间的传值
采用事件总线:
通过定义一个空白的对象 所有的事件派发和监听都在这个对象上进行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>平行组件间的传值</title>
<style>
img{width: 50px;height:50px;}
ul li{list-style: none;float: left;margin-left: 20px;color: hotpink}
.products{height: 200px;width: 500px;border: 1px solid hotpink}
</style>
</head>
<body>
<div id="app">
<!-- 顶部导航 -->
<navbar></navbar>
<br/>
<!-- 商品列表 -->
<products v-for="(p,i) in list" :key="i" :products="p"></products>
</div>
<script src="./libs/vue.js"></script>
<script>
const eventBus=new Vue()//事件总线
const navbar ={
template:`<div>
<ul>
<li>首页</li>
<li>商品类别</li>
<li>购物车({{count}})</li>
</ul>
</div>`,
created() {
eventBus.$on('buy',this.buyProduct)
console.log("监听")
},
methods: {
buyProduct(v){
this.count +=1
}
},
data(){
return{
count:0
}
}
}
const products ={
template:`<div class="products">
<img :src='products.img'/>
<h5>{{products.name}}</h5>
<p>{{products.price}}</p>
<button @click="buyHandle(products)">购买</button>
</div>`,
props:['products'],
methods: {
buyHandle(p){
eventBus.$emit('buy',p)
console.log("派发")
}
},
}
var app = new Vue({
el:'#app',
data:{
list:[{
img:'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2276391059,2676039382&fm=27&gp=0.jpg',
name:'仓鼠',
price:'¥2000'
},{
img:'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1969255128,1774348070&fm=27&gp=0.jpg',
name:'狗狗',
price:'¥3000'
},{
img:'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3286892623,1469273490&fm=27&gp=0.jpg',
name:'猫',
price:'¥5000'
}]
},
components:{
navbar:navbar,
products:products
}
})
</script>
</body>
</html>