vue全局組件與局部組件使用方法詳解
vue全局/局部注冊,以及一些混淆的組件
main.js入口文件的一些常用配置, 在入口文件上定義的public.vue為全局組件,在這里用的是pug模版 .wraper 的形式相當于<div class=wraper></div>
—main.js文件
**main.js入口文件的內(nèi)容** import Vue from 'vue' import App from './App' import router from './router' // 引入公用組件的vue文件 他暴漏的是一個對象 import cpublic from './components/public' Vue.config.productionTip = false // 注冊全局組件-要在vue的根事咧之前 // 參數(shù) 1是標簽名字-string 2是對象 引入外部vue文件就相當與一個對象 Vue.component('public', cpublic) // 正常注冊全局組件的時候,第二個參數(shù)應該是對象。 Vue.component('public1', { template: '<div>正常的組件模式</div>' }) /* eslint-disable no-new */ // 生成vue 的根實例;創(chuàng)建每個組件都會生成一個vue的事咧 new Vue({ el: '#app', router, template: '<App/>', components: { App } })
—public.vue 組件為定義的全局組件在任何組件里都可以直接使用,不需要在vue實例選項components上在次定義,也不需要再次導入文件路徑。
**public.vue的組件內(nèi)容** <template lang="pug"> .wrapper slot(text="我是全局組件") {{name}} </template> <script> export default { name: 'HelloWor', // 全局組件里data屬性必須是函數(shù),這樣才會獨立, // 在組件改變狀態(tài)的時候不會影響其他組件里公用的這個狀態(tài) data () { return { name: '我是全局組件' } } } </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 我是父組件的內(nèi)容 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將數(shù)據(jù)傳遞到子組件,并與v-model想對應的輸入框相互綁定。 msg: '這個是父組件的-prop-數(shù)據(jù)' } }, components: { children } } </script> <style scoped> .wrap { } .input-hd { display: flex; flex-direction: row; align-items: center; height: 70px; } </style>
children.vue是parent.vue的子組件,但是只在parent.vue作用域里可用
<template lang="pug"> .wrapper slot(text="我是子組件的text") 我是子組件的內(nèi)容 .name {{ msg }} {{ number }} </template> <script> export default { name: 'HelloWor', // 接受的時候是用props接受,數(shù)組的形式,里面是字符串的形式。 // 也可以傳入普通的字符串 // 在子組件中,props接受到的狀態(tài)當作vue的實例屬性來使用 props: [ 'msg', 'number' ] } </script> <style scoped> </style>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
VUE中如何調(diào)用高德地圖獲取當前位置(VUE2.0和3.0通用)
使用uniapp開發(fā)微信小程序時,多多少少會遇到獲取當前位置的詳細信息,下面這篇文章主要給大家介紹了關(guān)于VUE中如何調(diào)用高德地圖獲取當前位置(VUE2.0和3.0通用)的相關(guān)資料,需要的朋友可以參考下2023-04-04vue動態(tài)路由:路由參數(shù)改變,視圖不更新問題的解決
今天小編就為大家分享一篇vue動態(tài)路由:路由參數(shù)改變,視圖不更新問題的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11vue單頁應用的內(nèi)存泄露定位和修復問題小結(jié)
系統(tǒng)進程不再用到的內(nèi)存,沒有及時釋放,就叫做內(nèi)存泄漏(memory leak)。這篇文章主要介紹了vue單頁應用的內(nèi)存泄露定位和修復,需要的朋友可以參考下2019-08-08vue-extend和vue-component注冊一個全局組件方式
這篇文章主要介紹了vue-extend和vue-component注冊一個全局組件方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11詳解vue中$nextTick和$forceUpdate的用法
這篇文章主要介紹了詳解vue中$nextTick和$forceUpdate的用法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12