這篇文章主要爲大家詳細介紹了vue全局組件與局部組件的使用方法,具有一定的參考價值,對此有需要的朋友可以參考學習下。如有不足之處,歡迎批評指正。
vue全局/局部註冊,以及一些混淆的組件
main.js入口文件的一些常用配置, 在入口文件上定義的public.vue爲全局組件,在這裏用的是pug模版 .wraper 的形式相當於<div class=wraper></div>
—main.js文件
**main.js入口文件的內容**
import Vue from 'vue'
import App from './App'
import router from './router'
// 引入公用組件的vue文件 他暴漏的是一個對象
import cpublic from './components/public'
Vue.config.productionTip = false
// 註冊全局組件-要在vue的根事咧之前
// 參數 1是標籤名字-string 2是對象 引入外部vue文件就相當與一個對象
Vue.component('public', cpublic)
// 正常註冊全局組件的時候,第二個參數應該是對象。
Vue.component('public1', {
template: '<div>正常的組件模式</div>'
})
/* eslint-disable no-new */
// 生成vue 的根實例;創建每個組件都會生成一個vue的事咧
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
—public.vue 組件爲定義的全局組件在任何組件裏都可以直接使用,不需要在vue實例選項components上在次定義,也不需要再次導入文件路徑。
**public.vue的組件內容**
<template lang="pug">
.wrapper
slot(text="我是全局組件") {{name}}
</template>
<script>
export default {
name: 'HelloWor',
// 全局組件裏data屬性必須是函數,這樣纔會獨立,
// 在組件改變狀態的時候不會影響其他組件裏公用的這個狀態
data () {
return {
name: '我是全局組件'
}//歡迎加入前端全棧開發交流圈一起學習交流:864305860
}//面向1-3年前端人員
}//幫助突破技術瓶頸,提升思維能力
</script>
<style scoped>
</style>
在parent.vue組件裏,用到了public全局組件以及其他的子組件
parent.vue組件
<template lang="pug">
.wrap
.input-hd
.title 名稱:
input.input(type="text",v-model="msg",placeholder="請輸入正確的值",style="outline:none;")
.content-detail
.content-name 我是父組件的內容
children(:msg='msg', number='1')
public
router-link(to='/parent/children2') 第二個子組件
router-view
</template>
<script>
import children from './children'
// children(:msg='msg', number='1')在組件裏 也可以傳遞自定義的屬性,但是是字符串類型,
export default {
name: 'HelloWor',
data () {
return {
// 通過prop將數據傳遞到子組件,並與v-model想對應的輸入框相互綁定。
msg: '這個是父組件的-prop-數據'
}
},
components: {
children
}
}
</script>
<style scoped>
.wrap {
}
.input-hd {
display: flex;
flex-direction: row;
align-items: center;
height: 70px;
}//歡迎加入前端全棧開發交流圈一起學習交流:864305860
</style>
children.vue是parent.vue的子組件,但是隻在parent.vue作用域裏可用
<template lang="pug">
.wrapper
slot(text="我是子組件的text") 我是子組件的內容
.name {{ msg }} {{ number }}
</template>
<script>
export default {
name: 'HelloWor',
// 接受的時候是用props接受,數組的形式,裏面是字符串的形式。
// 也可以傳入普通的字符串
// 在子組件中,props接受到的狀態當作vue的實例屬性來使用
props: [ 'msg', 'number' ]
}
</script>
//歡迎加入前端全棧開發交流圈一起學習交流:864305860
<style scoped>
//幫助突破技術瓶頸,提升思維能力
</style>
結語
感謝您的觀看,如有不足之處,歡迎批評指正。
本次給大家推薦一個免費的學習羣,裏面概括移動應用網站開發,css,html,webpack,vue node angular以及面試資源等。對web開發技術感興趣的同學,歡迎加入Q羣:864305860,不管你是小白還是大牛我都歡迎,還有大牛整理的一套高效率學習路線和教程與您免費分享,同時每天更新視頻資料。
最後,祝大家早日學有所成,拿到滿意offer,快速升職加薪,走上人生巔峯。