写在前面:
1. 父组件的 data 写法与子组件的 data 写法不同
- //父组件
- data:{
- //对象形式
- }
- //子组件
- data:function(){
- return {
- //函数形式
- }
- }
2. 引用子组件遵循
以下实例全部使用以下模板
- //父组件
- {
- {
- total
- }
- } < mime@increment1 = "incrementTotal"ref = "child": num - a = "total"num - s = "total" > </mime>
- 调用子组件
- / / 子组件 < template id = "myInput" > <button@click = "add" > {
- {
- counter
- }
- } < /button>
- </template > new vue({
- el: '#app',
- data: {
- total: 0
- },
- methods: {
- incrementTotal: function() {
- },
- clickref: function() {
- }
- },
- components: {
- 'mime': {
- template: '#myInput',
- data: function() {
- return {
- counter: 0
- }
- },
- props: ['numA', 'numS'],
- methods: {
- add: function() {
- }
- }
- }
- }
- });
1. 父子通信 之 静态数据
如果只是传单一的字符串
- ....
- props:['numS'] // numS 为字符串 total
这样子组件的 numS 一直为 total。但这种太不灵活
2. 父子通信 之 动态数据
父组件的数据将会动态传递给子组件
- ....
- //props:['numA']
- props:{
- numA:[ String , Number ] //允许字符串 数字
- }
这时当 input 输入什么,子组件的 numA 将会得到什么
3. 父子通信 之 子调用父
- {{total}}
- ...
- ....
- data:{
- tatal: 0
- },
- methods:{
- incrementTotal:function(){
- this.total +=1;
- }
- },
- components:{
- data : function(){
- return:{
- counter : 0
- }
- },
- methods : {
- add : function(){
- this.counter +=1;
- this.$emit('increment'); //子组件通过 $emit触发父组件的方法 increment 还可以传参 this.$emit('increment' ,this.counter);
- }
- }
- }
子组件执行 add --> 触发 $emit --> 触发父组件 increment --> 执行 incrementTotal 方法
4. 父子通信 之 父调用子
- 调用子组件
- ...
- ....
- methods:{
- clickref:function(){
- var child = this.$refs.child; //获取子组件实例
- child.counter = 45; //改变子组件数据
- child.add(11); //调用子组件方法 add
- }
- },
- components:{
- data : function(){
- return:{
- counter : 0
- }
- },
- methods : {
- add : function(num){
- this.counter +=1;
- console.log('接受父组件的值:',num) //num为11
- }
- }
- }
通过在子组件上引用 ref, 从而获得子组件实例,进行相应操作。
5. 子组件与子组件通信
官网:在简单的场景下,使用一个空的 Vue 实例作为中央事件总线
- var bus = new Vue()
- // 触发组件 A 中的事件
- bus.$emit('id-selected', 1)
- // 在组件 B 创建的钩子中监听事件
- bus.$on('id-selected',
- function(id) {
- // ...
- })
但是这样实在太麻烦了,建议使用
来源: http://www.cnblogs.com/QRL909109/p/6166209.html