day62

一.组件

  • 组件都具有模板,template
  • new Vue()创建的是根组件
  • 组件与实例一一对应,创建一个实例就是创建了一个组件,同理创建一个组件就相当于创建了一个实例
  • 根组件的挂载点一般就是根组件的模板,根组件也可以显式书写自己的模板,会替换掉挂载点
  • 子组件都具有自身模板,根组件是所有子组件的父级(一级父级....n级父级)

二.局部组件

<div id="app">
    <!-- 连接语法 -->
    <local-tag></local-tag>
</div>
<script>
	// 定义局部组件
    var localTag = {
        template: "<button @click='btnClick'>{{ num }}</button>",
        data () {
    		return {
        		num: 0
    		}
    	},
        methods: {
            btnClick () {
                this.num++;
            }
        }
    }
    
    
	// 根组件
    new Vue({
    	el: "#app",
        // 子组件要在父组件中使用,需要注册
        components: {
            // 小驼峰 "localTag": localTag
            localTag
        }
    })
</script>

三.全局组件

<div id="app">
    <global-tag></global-tag>
</div>
<script>
    // 定义全局组件
    Vue.component("global-tag",{
    	template: "<button @click='btn'>{{ n }}</button>",
        data () {
            return {
                n: 0
            }
        },
        methods: {
            btn () {
                this.n++
            }
        }
    })
    
	// 根组件
    new Vue({
    	el: "#app",
    })
</script>

四.数据传递~父传子

<div id="app">
    <local-tag :num="num" :sup_data="sup_data"></local-tag>
</div>
<script type="text/javascript">
	var localTag = {
		props: ['num', 'sup_data'],
		template: "<div @click='divActive'>{{ num }}</div>",
		methods: {
			divActive () {
				console.log(this.num);
				console.log(this.sup_data);
			}
		}
	}

	new Vue({
		el: "#app",
		components: {
			localTag
		},
		data: {
			num: 10,
			sup_data: [1, 2, 3, 4, 5]
		}
	})
</script>
// 1.数据由父级提供
// 2.在父级模板(挂载点)中出现的子组件名(local-tag)上,为其设置全局属性,属性值就是父级提供的数据变量
// 3.在子组件中,提供$props来拿到自身的全局属性名(用''括起来的数组)
// 4.在模板中直接用属性名来访问数据,在方法中通过this.属性名来访问数据
// 5.名字出现多个单词的时候,使用_连接语法进行处理,以达到命名的统一

五.数据传递~子传父

<div id="app">
    <global-tag @send_data="receive_data"></global-tag>
    {{ n }}
</div>
<script type="text/javascript">
	Vue.component("global-tag", {
		template: "<div @click='divAction'>我是div</div>",
		data () {
			return {
				num: 10,
				arrList: [1, 2, 3, 4, 5]
			}
		},
		methods: {
			divAction () {
				this.$emit("send_data", this.num, this.arrList)
			}
		}
	});

	new Vue({
		el: "#app",
		data: {
			n: 0
		},
		methods: {
			receive_data (num, arrList) {
				console.log("接收到的数据:", num, arrList);
				this.n = num;
			}
		}
	})
</script>
// 1.数据由子级提供
// 2.在子级中通过某个事件对外(this.$emit("事件名", ...args))发送一个事件
// 3.在父级的模板中,子组件名上,为发送的事件绑定一个回调方法,该回调方法由父级来完成实现体
// 4.在实现体中就可以拿到回调参数
posted @ 2018-10-30 19:58  yyxxff  阅读(97)  评论(0编辑  收藏  举报