vue的所有功能模块,都可以抽出来作为组件去使用。
组件化的好处:
1 提高代码的复用性,一个页面如果有多个重复的,可以使用组件。组件之间的数据样式相互独立,互不干扰。
2 有利于代码的维护。当页面代码比较多比较复杂的时候,如果涉及到代码的修改,只需要关注对应组件的修改,不会影响其他。
3 灵活。组件还可以嵌套组件,可以把各种功能根据自己的需要灵活拆分组合。
vue中简单使用组件化:
1 把一个功能抽出来,放到js文件里,作为组件
2 在使用的页面通过import引入,通过components属性去注册,就可以直接使用
代码示例:
组件:Button.js
export default {
data(){
return {
msg:'我是组件'
}
},
template:`
<div style='width:100px;height:20px;
text-align:center;
border:1px solid #ccc'>{{msg}}</div>
`
}
引入App.js使用:
import Button from "./Button"
export default {
data(){
return {
msg:'hello vue'
}
},
components:{Button},
template:`
<div>
<h2>{{msg}}</h2>
<Button />
</div>
`
}
App.js 引入index.js注册使用:
// 引入vue
import { createApp } from "vue/dist/vue.esm-bundler.js";
import App from './app.js'
// 实例化并挂载到页面
createApp(App).mount('#app')
页面结构:
页面效果: