Vue實(shí)例是Vue應(yīng)用的啟動(dòng)器庸追,Vue組件是Vue實(shí)例的擴(kuò)展巫橄。
1. Vue實(shí)例
通過構(gòu)造函數(shù)可以創(chuàng)建一個(gè)Vue的根實(shí)例椒拗。
SPA應(yīng)用中膀斋,只會(huì)創(chuàng)建一個(gè)Vue根實(shí)例梭伐,應(yīng)用都是通過這個(gè)根實(shí)例啟動(dòng)的。
實(shí)例化 Vue 時(shí)仰担,需要傳入一個(gè)選項(xiàng)對(duì)象糊识,它可以包含數(shù)據(jù)(data),模板(template)摔蓝,掛載元素(el)赂苗,方法(methods)與生命周期鉤子函數(shù)(created,mounted...)等選項(xiàng)贮尉。下面是一個(gè)真實(shí)項(xiàng)目中定義的Vue實(shí)例:
import Vue from 'vue';
import App from './App.vue'
...
// 激活Vue調(diào)試工具vue-devtools
Vue.config.devtools = true;
new Vue({
router, // react-router
store, // vuex
el: '#app', // 需要渲染的DOM節(jié)點(diǎn)
render: h => h(App) // //h是createElement 的別名拌滋,創(chuàng)建/加載組件
});
2. Vue組件
Vue組件是被擴(kuò)展的Vue實(shí)例,同Vue實(shí)例類似猜谚,它也需要傳入一個(gè)選項(xiàng)對(duì)象败砂,包含數(shù)據(jù),模板魏铅,生命周期鉤子函數(shù)等等昌犹。
組件分為局部組件和全局組件。
(1)局部組件
局部組件只能在所定義的Vue實(shí)例中使用览芳,格式如下:
//定義<my-component>組件
new Vue({
// ...
components: {
// <my-component> 將只在父模板可用
'my-component': {
template: '<div>A custom component!</div>'
}
}
})
(2)全局組件
第一種方式:利用Vue提供的靜態(tài)函數(shù)component
注冊(cè):
Vue.component('my-component', {
template: '<div>A custom component!</div>',
//必須是用函數(shù)返回?cái)?shù)據(jù)模型斜姥,這樣才能讓多個(gè)組件實(shí)例擁有自己的數(shù)據(jù)模型
data: function () {
return data;
}
})
第二種方式:?jiǎn)挝募M件
定義一個(gè)后綴為.vue
的文件,利用webpack編譯處理沧竟。
單文件組件的最大優(yōu)點(diǎn)是疾渴,可以將組件相關(guān)的HTML,CSS屯仗,JS都定義在.vue
文件內(nèi),默認(rèn)支持CSS模塊化(樣式僅在該組件內(nèi)有效)搔谴,JavaScript模塊化(CommonJs模塊)魁袜。
參考官網(wǎng)例子:
注意,<style>
有scope
屬性后敦第,能夠?qū)?biāo)簽內(nèi)部的CSS選擇器自動(dòng)加上后綴峰弹,使其僅應(yīng)用在此組件內(nèi)。下圖是編譯后的組件內(nèi)聯(lián)樣式:
vue文件組件也支持CSS預(yù)處理語言芜果,比如scss或者less鞠呈。如需使用scss,定義lang
屬性即可:
<style lang="scss" scoped>...</style>
webpack.config中需要加載vue-loader來解析.vue
文件(下面配置支持在vue組件中使用scss語法)右钾。
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this necessary.
'scss': 'vue-style-loader!css-loader!sass-loader',
'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
}
// other vue-loader options go here
}
},
......
]
},
小結(jié)
建議采用單文件組件方式創(chuàng)建Vue項(xiàng)目蚁吝,這樣可以更好的和路由插件配合旱爆。
隨著項(xiàng)目不斷迭代,組件復(fù)雜度會(huì)隨之增加窘茁,單文件組件有著更好的可讀性和可擴(kuò)展性怀伦,非常適合大中型項(xiàng)目。
下一節(jié):Vue入門系列(三)Vue實(shí)例的生命周期
更多高階內(nèi)容山林,可移步《小專欄-娜姐聊前端》房待。