父向子传值
说明:子组件通过props声明属性,父组件绑定属性值,子组件获取属性值,再将值传递给data声明属性。
<div id="app">
<div>
<div>我是父组件div>
<my-child-cpn :number="fatherNum">my-child-cpn>
div>
div>
<template type="text/x-template" id="childTemplate">
<div>
<div>我是子组件div>
<div>父组件传递的值:{{childNumber}}div>
<div>
<button @click="increase">增加button>
<button @click="decrease">减少button>
div>
div>
template>//js部分
Vue.component('my-child-cpn', {
template: '#childTemplate',
props: ['number'],
data() {
return {
childNumber: this.number
}
},
methods: {
increase() {
this.childNumber++
},
decrease(){
this.childNumber--
}
}
})
//root组件
var vm = new Vue({
el: "#app",
data:{
fatherNum:1
}
})备注:data 为组件自身的属性,数据可读可写; prop 为接收父级的属性,数据为仅读的。
子向父传值
说明:子组件通过$emit触发事件,参数为传递属性值,父组件监听该事件,通过回调函数参数形式获取。
<div id="app">
<div>
<div>我是父组件div>
<my-child-cpn :number="fatherNum" @get-number="getChildNumber">my-child-cpn>
div>
div>
<template type="text/x-template" id="childTemplate">
<div>
<div>我是子组件div>
<div>父组件传递的值:{{childNumber}}div>
<div>
<button @click="increase">增加button>
<button @click="decrease">减少button>
div>
div>
template>//js部分
Vue.component('my-child-cpn', {
template: '#childTemplate',
props: ['number'],
data: function() {
return {
childNumber: this.number
}
},
methods: {
increase() {
this.childNumber++
this.$emit('get-number', this.childNumber)
},
decrease(){
this.childNumber--
this.$emit('get-number', this.childNumber)
}
}
})
//root组件
var vm = new Vue({
el: "#app",
data:{
fatherNum:1
},
methods: {
getChildNumber: function(number) {
alert("子组件属性改变后的值为:"+number)
}
}
})备注:vue中的数据是单向传递的,只能自上而下,不能自下而上,但可监听方法回调方式传值。
04-06
516