组件components
全局组件
app.component 来创建组件:
const app = Vue.createApp({
})
app.component("btn",{
template:`<button @click="n++">{ {n}}</button>`,
data(){return {n:1}}
})
app.mount("#app")
局部组件
const step = {
template:`<div><button @click="n--">-</button>{ {n}}<button @click="n++">+</button></div>`,
data(){return {n:1}}
}
const app = Vue.createApp({
components:{step}
})
<step></step>
<step></step>
我们来讲个最简单的 父亲,儿子 ,孙子的 例子
要注意以下几点:
1.先实例化对象vm
2.造出parent模板,并挂载在 vm的 conponents 下
3.造出 son 模板 并 挂载 在 父级 parent 的conponents下,并在 父级template属性中 包裹住自己的 模板名标签 ;同理 造出孙子标签
4.在HTML节点中添加 目标 根节点
(节点的顺序一定要书写正确)
<div id="app">
<parent></parent>
</div>
//创建 孙子 模板
let grendson = {
template:"<div>孙子</div>"
}
//创建 儿子 模板
let son= {
template:"<son>儿子<grendson >孙子</grendson ></son>"
components:{
grendson
}
}
//创建 父亲 模板
let parent = {
template:"<div>父亲<son></son></div>"
components:{
son
}
}
//实例化vm对象
let vm = new Vue({
el:"#app",
data:{
},
components:{
parent
}
});
props传递参数
<step :num="10"></step>
<step :num="5"></step>
props:{
"num":{type:Number,default:1}
},
data(){return {n:this.num}}