父向子传值主要通过的是props属性来传值,props只读
<!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>父组件向子组件传值--props</title>
<script src="./js/vue.min.js"></script>
</head>
<body>
<div id="app">
<menu-item title="来自父组件的值"></menu-item>
<!-- 在子组件身上绑定自定义属性来接收父组件data中的数据 -->
<menu-item :tit="title"></menu-item>
</div>
<script>
Vue.component('menu-item',{
props:['tit'], //props用来接收父组件传过来的值
//在props中使用驼峰形式,模版中要改为使用短横线拼接 props里面的值只读,不能修改
//props是单向数据流
data(){
return{
}
},
template:'<div>{{tit}}</div>'
})
var vm=new Vue({
el:'#app',
data:{
title:'我是父组件中的数据'
},
methods:{
}
});
</script>
</body>
</html>
子向父传值 $emit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 父组件 -->
<div :style='{fontSize:fontSize+"px"}'>{{pmsg}}</div>
<!-- 子组件 -->
<menu-item :parr="parr" @aas="blune"></menu-item>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
/*
子组件向父组件传值-基本用法
props传递数据原则:单向数据流
*/
Vue.component('menu-item', {
props:['parr'],
data(){
return {
msg1:'这是子组件传递过来的值'
}
},
template: `
<div>
<ul>
<li v-for="(item,index) in parr" :key="index">{{item}}</li>
</ul>
<button @click='dd'>扩大父组件中字体大小</button>
</div>
`,
methods:{
dd(){
this.$emit("aas",this.msg1)
}
}
});
//$emit
var vm = new Vue({
el: '#app',
data: {
pmsg: '父组件中内容',
parr: ['apple','orange','banana'],
fontSize: 10
},
methods: {
blune(message){
this.fontSize+=5;
console.log(message);
}
}
});
</script>
</body>
</html>
兄弟组件传值
<!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>Document</title>
<script src="./js/vue.min.js"></script>
</head>
<body>
<div id="app">
<brother></brother>
<sister></sister>
</div>
<script>
var enveBus = new Vue();
Vue.component('brother', {
data() {
return {
kk: ''
}
},
methods: {
dd() {
enveBus.$emit("bTs", '这是哥哥给妹妹的爱')
}
},
template: `
<div>
<button @click='dd'>这是一个哥哥组件---{{kk}}</button>
</div>
`,
mounted() {
enveBus.$on('asd', (result) => {
this.kk = result;
})
}
});
Vue.component('sister', {
data() {
return {
sis: ''
}
},
template: `
<div>
<button @click="cc">这是一个妹妹组件---{{sis}}</button>
</div>
`,
mounted() {
enveBus.$on('bTs', (message) => {
this.sis = message
})
},
methods: {
cc() {
enveBus.$emit('asd', '这是妹妹对哥哥的爱');
}
}
});
var vm = new Vue({
el: '#app',
data: {
},
methods: {
}
});
</script>
</body>
</html>