3.组件化开发
3.1 什么是组件
那么什么是组件呢,这里我们可以理解为一个功能强大的标签。没错就是一个标签,跟我们的<div></div>等等一样使用。接下来来看看怎么写这么一个组件:
const app = Vue.createApp({
data(){
return {
msg:"hello world"
}
}
})
//以上是我们之前学过的 基础代码,下面来创建一个组件
app.component("hello",{ //第一个参数,是组件的名字
//定义模板 我们用模板字符串
template:`
<h1>hello component</h1>
`
})
//有个细节 这里挂载 必须在模板的下面执行,否则没有效果
app.mount('#app')
那么组件会写了,什么是组件化开发呢,通俗点讲就像是我们常看到一些官网,顶部有导航栏,两边可能又有一些什么栏目模块,中间是大块内容,那组件化就是把它们分别都定义成组件使用。
那我们继续讲组件,上面我们只是用到了它的template模板而已,它也可以跟Vue.createApp一样有data()、methods之类的。例如:
app.component("hello",{
data(){
return {
msg:'hello component'
}
},
methods:{
showData(){
alert("hello component again")
}
},
template:`
<h1>数据:{{msg}}</h1>
<button @click='showData'>按钮</button>
`
})
3.2 组件的嵌套、复用
复用其实很简单理解,像我们上面使用组件是直接将标签写上去<hello></hello>,复用的意思就是可以写很多个hello标签,在做项目的时候,为了页面的统一性一般来说 设计师在设计页面的时候会用到很多类似的东西 比如 同一个按钮,那一个按钮长得一样、功能一样,总不能每次要用都得重新写一个嘛,这就是组件化的用处了。
嵌套的话,下面写个例子就可以明白了,就拿上面的案例打比方,我们可以把按钮也单独作为一个组件,然后将按钮组件放到hello组件中:
app.component("hello",{
data(){
return {
msg:'hello component'
}
},
template:`
<h1>数据:{{msg}}</h1>
<newButton></newButton>
`
})
app.component("newButton",{
methods:{
showData(){
alert("hello newButton")
}
},
template:`
<button @click='showData'>按钮</button>
`
})
3.3 根组件与组件树的基本概念
回忆一下之前用的 .mount()
const app = Vue.createApp({})
//根组件
const rootComponent = app.mount("#app")//这里得到的就是一个根组件
在之前的案例中都是直接写:
Vue.createApp({
data(){},
methods:{}
}).mount('#app')
Vue的createApp,会创建一个vue应用的实例(理解为一个对象) ,然后将它.mount()挂载的返回值就是一个 根组件,意思就是它其实也是一个组件,所以我们发现 上面我们在写一个新组件的时候跟createApp这么类似。而用app.component()创建出来的呢都是这个根组件的 子组件。
那么组件树怎么理解呢,在3.2的嵌套例子中,我们有一个hello组件,有一个newButton组件,那我们树的根就是我们上面说的 根组件,他接下来的子组件就是 hello ,hello下面接着有 newButton,就像一棵树一样延申。
那在我们平时写代码的时候,总是用到 this,那createApp里面的this代表的是谁呢,其实里面的this代表的正是根组件。
那有的小伙伴可能要问了,“诶诶诶,那在用app.component()写组件的时候,里面有模板template呀,那根组件咋没有捏?”。其实是这样,因为我们把app.mount('#app') 挂载到 id='app' 的div上了,所以在<div id='app'>里面写的就是根组件的模板了。
3.4 全局组件与局部组件
全局组件:像我们之前,使用component方法注册的组件,叫做全局组件
局部组件:使用components属性实现局部组件
全局的我们之前学习过了,那么现在来实现一下注册局部组件:
//首先将我们想要的组件,写成对象
const hello = {
template:`
<h1>hello component</h1>
`
}
const newButton = {
template:`
<button>按钮</button>
`
}
//接着 用components属性 注册局部组件
const app = Vue.createApp({
components:{
"hello":hello,
"newButton":newButton
}
})
这样呢,我们就依然可以:
<div id='app'>
<hello></hello>
<newButton></newButton>
</div>
那么局部组件要怎么嵌套呢,上面我们看到,局部组件都是在根组件里面注册的,也就是说我在 hello 里是拿不到 newButton 的,因此如果想在hello里使用newButton,必须在 hello 里面也注册:
//那我们得把newButton写在上面,等下hello才能用
const newButton = {
template:`
<button>按钮</button>
`
}
const hello = {
components:{
"newButton":newButton
},
template:`
<h1>hello component</h1>
<newButton></newButton>
`
}
以后用到组件化开发的话,尽量是使用这个 局部组件components ,而不是app.component()。