如果你之前有了解过的话,那么只需要看前面这一部分!
终极思想
-
父向子传值 把握中间值props
- 子组件在props中创建一个属性,用以接收父组件传过来的值
- 父组件中注册子组件
- 在子组件标签中添加子组件props中创建的属性
- 把需要传给子组件的值赋给该属性
-
子向父传值 把握自定义函数的使用
- 子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件
- 将需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法
- 在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听
正文开始
父组件向子组件传递信息
<div id="app">
<Counter :count="num"></Counter>
<Counter :count="num"></Counter>
</div>
<template id="counter">
<div>
<button @click="n++">+</button>
{{n}}
</div>
</template>
<script>
Vue.component('Counter', {
props: ['count'],
template: "#counter",
data: function () {
return {
n: this.count
}
}
})
new Vue({
el: "#app",
data: {
num: 10
}
})
</script>
结果输出:
子向父组件传值
<!-- Prop 作为初始值传入后,子组件想把它当作局部数据来用; -->
<div id="app">
<p>父级total:{{total}}</p>
<button @click="incrementTotal">父级点击</button>
<hr>
<Counter v-on:increment="incrementTotal">
</Counter>
</div>
<template id="counter">
<div style="border:1px solid blue">
<button @click="increment">子级加
{{counter}}
</button>
</div>
</template>
<script>
Vue.component('Counter', {
template: "#counter",
data:function(){
return {counter:0}
},
methods:{
increment:function(){
this.counter += 1;
this.$emit("increment")
}
}
})
var vm = new Vue({
el: "#app",
data: {
total:0
},
methods:{
incrementTotal:function(){
this.total += 2
}
}
})
</script>
输出结果:
综合应用
<div id="app">
<com1 v-bind:parentmsg="msg" @func="getMsgFormSon"></com1>
</div>
<template id="tmpl">
<div>
<h1>这是子元素 --- {{ parentmsg }}</h1>
<input type="button" value="向父组件传递消息" @click="sendMsg">
</div>
</template>
<script>
var com1 = {
template: '#tmpl',
data() {
return {
msg: '做一个孝顺的孩子,给爸爸一些钱去挥霍吧!'
}
},
props: ['parentmsg'],
methods: {
sendMsg() {
this.$emit('func', this.msg)
}
}
}
// 创建 Vue 实例,得到 ViewModel
var vm = new Vue({
el: '#app',
data: {
msg: '这是父组件中的数据,爸爸有100块钱,my son, 你要不',
msgFormSon: ''
},
methods: {
getMsgFormSon(data) {
this.msgFormSon = data
console.log(this.msgFormSon)
}
},
components: {
com1
}
});
</script>