1.全局/局部组件
<whole></whole><moon></moon>
//下面是局部组件,局部组件需要在根组件中写入
var moon={
template:`<div><button @click="back">《=</button>局部组件<button >=》</button><img :src="url" alt=""></div>`,
data(){return{url:'http://pic.imeitou.com/uploads/allimg/230331/7-230331110I0.jpg'}},
methods:{back(){console.log('局部组件back')}},
}
//下面是全局组件
Vue.component('whole',{
template:`<div><button @click="back">《=</button>{{title}}<button >=》</button></div>`,
data(){return {title:'我是全局组件'}},
methods:{back(){console.log('back')}},
});
//根组件
let vm = new Vue({
el: "#app",data: {},methods: {},computed:{},watch:{},
components:{moon}//////////////这里面写局部组件
})
2组件间通信
通信值父传子
<moon :url='url'></moon>
//下面是局部组件
var moon={
template:`<div><button @click="back">《=</button>局部局部<button >=》</button><img :src="url" alt=""></div>`,
data(){return{}},
methods:{back(){console.log('局部局部back')}},
props:['url']
}
//根组件
let vm = new Vue({
el: "#app",
data: {url:'http://pic.imeitou.com/uploads/allimg/230331/7-230331110I0.jpg'},
methods: {},computed:{},watch:{},
components:{moon}//////////////这里面写局部组件
})
通信值子传父
image-20230606115516512.png
接受到的子组件输入的内容是:{{username}}
<moon @myevent="handelEvent"></moon>
//下面是局部组件
var moon={
template:`<div><button @click="handleSend">《=</button>局部局部<button >=》</button><img :src="url" alt=""><br>
<input type="text" v-model="username"></div>`,
data(){return{url: 'http://pic.imeitou.com/uploads/allimg/230331/7-230331110I0.jpg',username: ''}},
methods:{handleSend(){this.$emit('myevent', this.username)}},// 传递给父组件
props:['url']
}
//根组件
let vm = new Vue({
el: "#app",
data: {url:'http://pic.imeitou.com/uploads/allimg/230331/7-230331110I0.jpg'},
methods: {
handelEvent(username) {
console.log('父组件自定义事件的event执行了');console.log(username)
this.username = username
}
},computed:{},watch:{},
components:{moon}//////////////这里面写局部组件
})
3.ref属性
# ref属性,vue提供的,写在标签上
可以写在普通标签:在vue中使用 this.$refs.名字 拿到dom对象,可以原生操作
可以写在组件上:在vue中使用 this.$refs.名字 拿到[组件]对象,组件属性,方法直接使用即可
4动态组件
<button @click="who='home1'">1</button>
<button @click="who='home2'">2</button>
<button @click="who='home3'">3</button>
<component :is="who"></component>
var home1={template:`<h1>1</h1>`}
var home2={template:`<h1>2</h1>`}
var home3={template:`<h1>3</h1>`}
var vm=new Vue({
el:'#app',
data:{who:'home1'},
components:{home1,home2,home3}
})
4.1 keep-alive
<keep-alive> <component :is="who"></component></keep-alive>
5.插槽
使用步骤:
#1 在组件的html的任意位置,放个标签
<slot></slot>
# 2 后期在父组件使用该组件时
<lqz>
放内容
</lqz>
# 3 放的内容,就会被渲染到slot标签中
var lqz = {template: `<div><h1>我是一个组件</h1> <slot></slot><h2>我是组件内部的h2</h2></div>`}
var vm = new Vue({
el: '#app',data: {},components: { lqz,}
})
5.1 具名插槽
1 组件中可以留多个插槽,命名
<div>
<h1>我是一个组件</h1>
<slot name="middle"></slot>
<h2>我是组件内部的h2</h2>
<slot name="footer"></slot>
</div>
2 在父组件中使用时,指定某个标签渲染到某个插槽上
<lqz>
<div slot="footer">我是div</div>
<img slot="middle" src="https://scpic.chinaz.net/files/default/imgs/2023-05-12/23659b1edfc0a984.jpg" alt=""></lqz>
网友评论