向组件中插入内容有2种方式
vue.component('parent',{ template:` <!--反引号比引号更好用--> <div> <p>hello</p> <slot></slot> <!--如果后续要在组件中插入元素、内容,需要先留好槽点,不能直接插入--> </div> ` }) new vue({ el:'#app', template:` <div> <parent> <!--使用parent组件--> <p>i am chy </p> <!--使用组件时,组件标签的innerhtml会作为一个整体,替换槽点--> <p>nice to meet you</p> <!--必须要有槽点,不然innerhtml不知道放哪儿,无效--> </parent> </div> ` });
槽点未设置name时,使用该组件标签时,整个innerhtml都会被插入到槽点。slot是动态dom,innerhtml有多少内容,就插入多少内容。
如果不设置槽点,2个<p>元素不能插入到组件中。
vue.component('parent',{ template:` <div> <p>hello</p> <slot name="info"></slot> <!--槽点设置了name--> </div> ` }) new vue({ el:'#app', template:` <div> <parent> <!--使用parent组件--> <p slot="info">i am chy </p> <!--如果槽点设置了name,必须指定要插入的槽点--> <p>nice to meet you</p> <!--这个没有指定槽点,无效--> </parent> </div> ` });
vue.component('child',{ template:` <div> <p>i am chy</p> <p>nice to meet you</p> </div> ` }) vue.component('parent',{ template:` <div> <p>hello</p> <child></child> <!--子组件--> </div> ` }) new vue({ el:'#app', template:` <div> <parent></parent> </div> ` });
//子组件 vue.component('child',{ template:` <div> <p>i am chy</p> <p>nice to meet you</p> </div> `, data(){ return { msg:'this is the child' } }, mounted() { //生命周期方法,dom加载完成 console.log(this.$parent); //访问父组件对象|实例 } }) // 父组件 vue.component('parent',{ template:` <div> <p>hello</p> <child ref="son"></child> <!-- ref给子组件的引用起一个名字 --> </div> `, data(){ return { msg:'this is the parent' } }, mounted() { console.log(this.$refs.son); //访问子组件对象|实例:this.$refs.子组件的ref属性值 } }) new vue({ el:'#app', template:` <div> <parent></parent> </div> ` });
只要当前dom中有元素使用了ref属性,就可以使用 this.$refs.ref属性值 来获取对应的实例
常用的还有
如对本文有疑问, 点击进行留言回复!!
offset、client、scroll (width,height、left,top、X,Y)
网友评论