Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
組件是 vue.js最強(qiáng)大的功能之一,而組件實(shí)例的作用域是相互獨(dú)立的,這就意味著不同組件之間的數(shù)據(jù)無(wú)法相互引用。一般來(lái)說(shuō),組件可以有以下幾種關(guān)系:
如上圖所示,A 和 B、B 和 C、B 和 D 都是父子關(guān)系,C 和 D 是兄弟關(guān)系,A 和 C 是隔代關(guān)系(可能隔多代)。
針對(duì)不同的使用場(chǎng)景,如何選擇行之有效的通信方式?這是我們所要探討的主題。本文總結(jié)了vue組件間通信的幾種方式,如props、$emit/$on、vuex、$parent / $children、$attrs/$listeners和provide/inject,以通俗易懂的實(shí)例講述這其中的差別及使用場(chǎng)景,希望對(duì)小伙伴有些許幫助。
父組件A通過(guò)props的方式向子組件B傳遞,B to A 通過(guò)在 B 組件中 $emit, A 組件中 v-on 的方式實(shí)現(xiàn)。
1.父組件向子組件傳值
接下來(lái)我們通過(guò)一個(gè)例子,說(shuō)明父組件如何向子組件傳遞值:在子組件Users.vue中如何獲取父組件App.vue中的數(shù)據(jù) users:["Henry","Bucky","Emily"]
//App.vue父組件 <template> <div id="app"> <users v-bind:users="users"></users>//前者自定義名稱便于子組件調(diào)用,后者要傳遞數(shù)據(jù)名 </div> </template> <script> import Users from "./components/Users" export default { name: 'App', data(){ return{ users:["Henry","Bucky","Emily"] } }, components:{ "users":Users } } //users子組件 <template> <div class="hello"> <ul> <li v-for="user in users">{{user}}</li>//遍歷傳遞過(guò)來(lái)的值,然后呈現(xiàn)到頁(yè)面 </ul> </div> </template> <script> export default { name: 'HelloWorld', props:{ users:{ //這個(gè)就是父組件中子標(biāo)簽自定義名字 type:Array, required:true } } } </script>
總結(jié):父組件通過(guò)props向下傳遞數(shù)據(jù)給子組件。注:組件中的數(shù)據(jù)共有三種形式:data、props、computed
2.子組件向父組件傳值(通過(guò)事件形式)
接下來(lái)我們通過(guò)一個(gè)例子,說(shuō)明子組件如何向父組件傳遞值:當(dāng)我們點(diǎn)擊“Vue.js Demo”后,子組件向父組件傳遞值,文字由原來(lái)的“傳遞的是一個(gè)值”變成“子向父組件傳值”,實(shí)現(xiàn)子組件向父組件值的傳遞。
// 子組件 <template> <header> <h1 @click="changeTitle">{{title}}</h1>//綁定一個(gè)點(diǎn)擊事件 </header> </template> <script> export default { name: 'app-header', data() { return { title:"Vue.js Demo" } }, methods:{ changeTitle() { this.$emit("titleChanged","子向父組件傳值"); //自定義事件 傳遞值“子向父組件傳值” } } } </script> // 父組件 <template> <div id="app"> <app-header v-on:titleChanged="updateTitle" ></app-header> //與子組件titleChanged自定義事件保持一致 // updateTitle($event)接受傳遞過(guò)來(lái)的文字 <h2>{{title}}</h2> </div> </template> <script> import Header from "./components/Header" export default { name: 'App', data(){ return{ title:"傳遞的是一個(gè)值" } }, methods:{ updateTitle(e){ //聲明這個(gè)函數(shù) this.title=e; } }, components:{ "app-header":Header, } } </script>
總結(jié):子組件通過(guò)events給父組件發(fā)送消息,實(shí)際上就是子組件把自己的數(shù)據(jù)發(fā)送到父組件。
這種方法通過(guò)一個(gè)空的Vue實(shí)例作為中央事件總線(事件中心),用它來(lái)觸發(fā)事件和監(jiān)聽(tīng)事件,巧妙而輕量地實(shí)現(xiàn)了任何組件間的通信,包括父子、兄弟、跨級(jí)。當(dāng)我們的項(xiàng)目比較大時(shí),可以選擇更好的狀態(tài)管理解決方案vuex。
1.具體實(shí)現(xiàn)方式:
var Event=new Vue(); Event.$emit(事件名,數(shù)據(jù)); Event.$on(事件名,data=> {});
2.舉個(gè)例子
假設(shè)兄弟組件有三個(gè),分別是A、B、C組件,C組件如何獲取A或者B組件的數(shù)據(jù)
<div id="itany"> <my-a></my-a> <my-b></my-b> <my-c></my-c> </div> <template id="a"> <div> <h3>A組件:{{name}}</h3> <button @click="send">將數(shù)據(jù)發(fā)送給C組件</button> </div> </template> <template id="b"> <div> <h3>B組件:{{age}}</h3> <button @click="send">將數(shù)組發(fā)送給C組件</button> </div> </template> <template id="c"> <div> <h3>C組件:{{name}},{{age}}</h3> </div> </template> <script> var Event=new Vue();//定義一個(gè)空的Vue實(shí)例 var A={ template: '#a', data() { return { name: 'tom' } }, methods: { send() { Event.$emit('data-a', this.name); } } } var B={ template: '#b', data() { return { age: 20 } }, methods: { send() { Event.$emit('data-b', this.age); } } } var C={ template: '#c', data() { return { name: '', age: "" } }, mounted() { //在模板編譯完成后執(zhí)行 Event.$on('data-a',name=> { this.name=name; //箭頭函數(shù)內(nèi)部不會(huì)產(chǎn)生新的this,這邊如果不用=>,this指代Event }) Event.$on('data-b',age=> { this.age=age; }) } } var vm=new Vue({ el: '#itany', components: { 'my-a': A, 'my-b': B, 'my-c': C } }); </script>
$on 監(jiān)聽(tīng)了自定義事件 data-a和data-b,因?yàn)橛袝r(shí)不確定何時(shí)會(huì)觸發(fā)事件,一般會(huì)在 mounted 或 created 鉤子中來(lái)監(jiān)聽(tīng)。
1.簡(jiǎn)要介紹Vuex原理
Vuex實(shí)現(xiàn)了一個(gè)單向數(shù)據(jù)流,在全局擁有一個(gè)State存放數(shù)據(jù),當(dāng)組件要更改State中的數(shù)據(jù)時(shí),必須通過(guò)Mutation進(jìn)行,Mutation同時(shí)提供了訂閱者模式供外部插件調(diào)用獲取State數(shù)據(jù)的更新。而當(dāng)所有異步操作(常見(jiàn)于調(diào)用后端接口異步獲取更新數(shù)據(jù))或批量的同步操作需要走Action,但Action也是無(wú)法直接修改State的,還是需要通過(guò)Mutation來(lái)修改State的數(shù)據(jù)。最后,根據(jù)State的變化,渲染到視圖上。
2.簡(jiǎn)要介紹各模塊在流程中的功能:
3.Vuex與localStorage
vuex 是 vue 的狀態(tài)管理器,存儲(chǔ)的數(shù)據(jù)是響應(yīng)式的。但是并不會(huì)保存起來(lái),刷新之后就回到了初始狀態(tài),具體做法應(yīng)該在vuex里數(shù)據(jù)改變的時(shí)候把數(shù)據(jù)拷貝一份保存到localStorage里面,刷新之后,如果localStorage里有保存的數(shù)據(jù),取出來(lái)再替換store里的state。
let defaultCity="上海" try { // 用戶關(guān)閉了本地存儲(chǔ)功能,此時(shí)在外層加個(gè)try...catch if (!defaultCity){ defaultCity=JSON.parse(window.localStorage.getItem('defaultCity')) } }catch(e){} export default new Vuex.Store({ state: { city: defaultCity }, mutations: { changeCity(state, city) { state.city=city try { window.localStorage.setItem('defaultCity', JSON.stringify(state.city)); // 數(shù)據(jù)改變的時(shí)候把數(shù)據(jù)拷貝一份保存到localStorage里面 } catch (e) {} } } })
這里需要注意的是:由于vuex里,我們保存的狀態(tài),都是數(shù)組,而localStorage只支持字符串,所以需要用JSON轉(zhuǎn)換:
JSON.stringify(state.subscribeList); // array -> string JSON.parse(window.localStorage.getItem("subscribeList")); // string -> array
1.簡(jiǎn)介
多級(jí)組件嵌套需要傳遞數(shù)據(jù)時(shí),通常使用的方法是通過(guò)vuex。但如果僅僅是傳遞數(shù)據(jù),而不做中間處理,使用 vuex 處理,未免有點(diǎn)大材小用。為此Vue2.4 版本提供了另一種方法----$attrs/$listeners
接下來(lái)我們看個(gè)跨級(jí)通信的例子:
// index.vue <template> <div> <h2>浪里行舟</h2> <child-com1 :foo="foo" :boo="boo" :coo="coo" :doo="doo" title="前端工匠" ></child-com1> </div> </template> <script> const childCom1=()=> import("./childCom1.vue"); export default { components: { childCom1 }, data() { return { foo: "Javascript", boo: "Html", coo: "CSS", doo: "Vue" }; } }; </script> // childCom1.vue <template class="border"> <div> <p>foo: {{ foo }}</p> <p>childCom1的$attrs: {{ $attrs }}</p> <child-com2 v-bind="$attrs"></child-com2> </div> </template> <script> const childCom2=()=> import("./childCom2.vue"); export default { components: { childCom2 }, inheritAttrs: false, // 可以關(guān)閉自動(dòng)掛載到組件根元素上的沒(méi)有在props聲明的屬性 props: { foo: String // foo作為props屬性綁定 }, created() { console.log(this.$attrs); // { "boo": "Html", "coo": "CSS", "doo": "Vue", "title": "前端工匠" } } }; </script> // childCom2.vue <template> <div class="border"> <p>boo: {{ boo }}</p> <p>childCom2: {{ $attrs }}</p> <child-com3 v-bind="$attrs"></child-com3> </div> </template> <script> const childCom3=()=> import("./childCom3.vue"); export default { components: { childCom3 }, inheritAttrs: false, props: { boo: String }, created() { console.log(this.$attrs); // { "boo": "Html", "coo": "CSS", "doo": "Vue", "title": "前端工匠" } } }; </script> // childCom3.vue <template> <div class="border"> <p>childCom3: {{ $attrs }}</p> </div> </template> <script> export default { props: { coo: String, title: String } }; </script>
如上圖所示$attrs表示沒(méi)有繼承數(shù)據(jù)的對(duì)象,格式為{屬性名:屬性值}。Vue2.4提供了$attrs , $listeners 來(lái)傳遞數(shù)據(jù)與事件,跨級(jí)組件之間的通訊變得更簡(jiǎn)單。簡(jiǎn)單來(lái)說(shuō):$attrs與$listeners 是兩個(gè)對(duì)象,$attrs 里存放的是父組件中綁定的非 Props 屬性,$listeners里存放的是父組件中綁定的非原生事件。
1.簡(jiǎn)介
Vue2.2.0新增API,這對(duì)選項(xiàng)需要一起使用,以允許一個(gè)祖先組件向其所有子孫后代注入一個(gè)依賴,不論組件層次有多深,并在起上下游關(guān)系成立的時(shí)間里始終生效。一言而蔽之:祖先組件中通過(guò)provider來(lái)提供變量,然后在子孫組件中通過(guò)inject來(lái)注入變量。 provide / inject API 主要解決了跨級(jí)組件間的通信問(wèn)題,不過(guò)它的使用場(chǎng)景,主要是子組件獲取上級(jí)組件的狀態(tài),跨級(jí)組件間建立了一種主動(dòng)提供與依賴注入的關(guān)系。
2.舉個(gè)例子
假設(shè)有兩個(gè)組件: A.vue 和 B.vue,B 是 A 的子組件
// A.vue export default { provide: { name: '浪里行舟' } } // B.vue export default { inject: ['name'], mounted () { console.log(this.name); // 浪里行舟 } }
可以看到,在 A.vue 里,我們?cè)O(shè)置了一個(gè) provide: name,值為 浪里行舟,它的作用就是將 name 這個(gè)變量提供給它的所有子組件。而在 B.vue 中,通過(guò) inject 注入了從 A 組件中提供的 name 變量,那么在組件 B 中,就可以直接通過(guò) this.name 訪問(wèn)這個(gè)變量了,它的值也是浪里行舟。這就是 provide / inject API 最核心的用法。
需要注意的是:provide 和 inject 綁定并不是可響應(yīng)的。這是刻意為之的。然而,如果你傳入了一個(gè)可監(jiān)聽(tīng)的對(duì)象,那么其對(duì)象的屬性還是可響應(yīng)的----vue官方文檔 所以,上面 A.vue 的 name 如果改變了,B.vue 的 this.name 是不會(huì)改變的,仍然是 浪里行舟。
3.provide與inject 怎么實(shí)現(xiàn)數(shù)據(jù)響應(yīng)式
一般來(lái)說(shuō),有兩種辦法:
我們來(lái)看個(gè)例子:孫組件D、E和F獲取A組件傳遞過(guò)來(lái)的color值,并能實(shí)現(xiàn)數(shù)據(jù)響應(yīng)式變化,即A組件的color變化后,組件D、E、F不會(huì)跟著變(核心代碼如下:)
// A 組件 <div> <h1>A 組件</h1> <button @click="()=> changeColor()">改變color</button> <ChildrenB /> <ChildrenC /> </div> ...... data() { return { color: "blue" }; }, // provide() { // return { // theme: { // color: this.color //這種方式綁定的數(shù)據(jù)并不是可響應(yīng)的 // } // 即A組件的color變化后,組件D、E、F不會(huì)跟著變 // }; // }, provide() { return { theme: this//方法一:提供祖先組件的實(shí)例 }; }, methods: { changeColor(color) { if (color) { this.color=color; } else { this.color=this.color==="blue" ? "red" : "blue"; } } } // 方法二:使用2.6最新API Vue.observable 優(yōu)化響應(yīng)式 provide // provide() { // this.theme=Vue.observable({ // color: "blue" // }); // return { // theme: this.theme // }; // }, // methods: { // changeColor(color) { // if (color) { // this.theme.color=color; // } else { // this.theme.color=this.theme.color==="blue" ? "red" : "blue"; // } // } // } // F 組件 <template functional> <div class="border2"> <h3 :style="{ color: injections.theme.color }">F 組件</h3> </div> </template> <script> export default { inject: { theme: { //函數(shù)式組件取值不一樣 default: ()=> ({}) } } }; </script>
雖說(shuō)provide 和 inject 主要為高階插件/組件庫(kù)提供用例,但如果你能在業(yè)務(wù)中熟練運(yùn)用,可以達(dá)到事半功倍的效果!
需要注意的是:這兩種都是直接得到組件實(shí)例,使用后可以直接調(diào)用組件的方法或訪問(wèn)數(shù)據(jù)。我們先來(lái)看個(gè)用 ref來(lái)訪問(wèn)組件的例子:
// component-a 子組件 export default { data () { return { title: 'Vue.js' } }, methods: { sayHello () { window.alert('Hello'); } } } // 父組件 <template> <component-a ref="comA"></component-a> </template> <script> export default { mounted () { const comA=this.$refs.comA; console.log(comA.title); // Vue.js comA.sayHello(); // 彈窗 } } </script>
不過(guò),這兩種方法的弊端是,無(wú)法在跨級(jí)或兄弟間通信。
// parent.vue <component-a></component-a> <component-b></component-b> <component-b></component-b>
我們想在 component-a 中,訪問(wèn)到引用它的頁(yè)面中(這里就是 parent.vue)的兩個(gè) component-b 組件,那這種情況下,就得配置額外的插件或工具了,比如 Vuex 和 Bus 的解決方案。
常見(jiàn)使用場(chǎng)景可以分為三類:
們?cè)陂_(kāi)發(fā)項(xiàng)目時(shí)候經(jīng)常會(huì)遇到這樣的需求,提供一個(gè)可選擇的下拉框,下拉列表中提供了常見(jiàn)的選項(xiàng)。當(dāng)所提供選項(xiàng)選項(xiàng)無(wú)法滿足用戶需求時(shí)用戶可以自行輸入所需參數(shù)。為了滿足大部分的用戶需求我們可以封裝一個(gè)通用組件來(lái)滿足多種需求,當(dāng)調(diào)用的組件的時(shí)候配置好參數(shù)就可以快速實(shí)現(xiàn)所需功能了。
圖來(lái)自“互聯(lián)網(wǎng)”
1,可定義組件寬度,下拉寬度與組件寬度一致;類型number,默認(rèn)值100;
2,可定義后綴,默認(rèn)為空;
3,可定義是否只讀,默認(rèn)為false;
4,可定義下拉列表選項(xiàng),類型數(shù)組,默認(rèn)為空;
5,可定義輸入框中值顯示位置,分別為居左、居中、居右;分隊(duì)對(duì)應(yīng)的可輸入值為left、center、right,默認(rèn)居中即center。
6,可定義下拉按鈕顯示,類型布爾值,默認(rèn)為true(顯示)。
這里利用了element中的popover彈出框組件中嵌套下拉列表來(lái)實(shí)現(xiàn)下拉選項(xiàng),當(dāng)選擇下拉選項(xiàng)中的值時(shí)將該值賦值給input框中的綁定值。而input框主要使用了些動(dòng)態(tài)樣式并監(jiān)聽(tīng)了鼠標(biāo)獲取焦點(diǎn)、鍵盤輸入、鍵盤刪除、鼠標(biāo)失去焦點(diǎn)等觸發(fā)事件 ,來(lái)實(shí)時(shí)改變輸入框中顯示的值。
這里我用的是scss預(yù)處理器,在修改popover組件樣式時(shí)我們用到了深度作用選擇器::v-deep,具體的可以參考文章Vue實(shí)戰(zhàn)072:CSS樣式中的各種深度作用選擇器的使用,這里需要注意的是控制彈出框與input框的寬度一致,在popover組件上添加一個(gè)樣式獲取上級(jí)組件的寬度以達(dá)到控制彈出窗父級(jí)組件的寬度,這樣popover中就可以獲取到父級(jí)組件的寬度,再通過(guò)深度作用選擇器來(lái)定位組件中的DOM元素并進(jìn)行修改即可。
props中是留給用戶調(diào)用組件時(shí)配置的參數(shù)值,前面文章Vue實(shí)戰(zhàn)071:Element實(shí)現(xiàn)WEB顏色選擇器功能中有提到過(guò)prop傳遞過(guò)來(lái)的值都是單向下行綁定,子組件不能修改由父組件傳遞過(guò)來(lái)的值。所以這里我們同樣定義一個(gè)變量來(lái)接受父級(jí)傳遞過(guò)來(lái)的值,然后通過(guò)計(jì)算屬性拼接后綴顯示。當(dāng)選擇下拉選項(xiàng)中的值時(shí)將該值在復(fù)制給變量,同時(shí)監(jiān)聽(tīng)顯示值的變化并通過(guò)this.$emit將該值傳遞給父級(jí)組件。
組件中只有下拉列表必須提供數(shù)據(jù)的,其他參數(shù)都定義了默認(rèn)值所以可選填。這樣用戶就可以非常靈活的使用該組件了,也大大提高了組件的可使用范圍。這里沒(méi)看到組件引入是因?yàn)槲覍?duì)組件進(jìn)行了全局自動(dòng)化注冊(cè),可以參考文章Vue實(shí)戰(zhàn)070:組件的局部注冊(cè)和全局注冊(cè)(含自動(dòng)化注冊(cè))功能實(shí)現(xiàn)。
以上內(nèi)容是小編給大家分享的Vue實(shí)戰(zhàn)073:可輸入的下拉框組件功能實(shí)現(xiàn),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。更多Vue實(shí)戰(zhàn)技巧可以參考專欄:Vue實(shí)戰(zhàn)系列,在此也非常感謝大家對(duì)小編的支持!
項(xiàng)目中,我們有時(shí)需要封裝一些組件,為了高內(nèi)聚,我們有時(shí)可以把文件都寫法一個(gè)js文件中。vite官方給我們提供了jsx寫法插件 @vitejs/plugin-vue-jsx,并且可以隨便找個(gè)css in js 庫(kù),這里我用@styils/vue
使用插件步驟:
npm i @vitejs/plugin-vue-jsx
npm i @styils/vue
//vite.config.js
// 引入jsx官方插件
import vueJsx from '@vitejs/plugin-vue-jsx'
export default defineConfig({
plugins: [
//更多配置看github
vueJsx({
include:/\.[jt]s$/
})
]
})
示例:
// App.vue
<template>
<div>
<el-button @click="Alerst" type="primary">彈框</el-button>
</div>
</template>
<script setup>
import { alert } from './utils/Alert'
const messageProp='彈出框數(shù)據(jù)'
const Alerst=()=> {
alert(messageProp)
}
</script>
// src/utils/Alert/index.js
import { render } from 'vue'
import { styled } from '@styils/vue';
export const alert=(propsData)=> {
//創(chuàng)建一個(gè)有樣式div
const Mydiv=styled('div', {
position: "fixed",
top: '50%',
left: '50%',
transform: 'translate(-50%,-50%)',
})
const container=document.createElement('div')
document.body.appendChild(container)
const VNode=(
<Mydiv> //替換原來(lái)沒(méi)有樣式的<div>
<h1>登錄成功</h1>
<p>{propsData}</p>
<button onClick={()=> {
container.remove();
}}>關(guān)閉</button>
</Mydiv>
)
render(VNode, container)
}
效果
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。