溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

發(fā)布時(shí)間:2023-05-20 11:34:40 來源:億速云 閱讀:139 作者:iii 欄目:編程語言

本篇內(nèi)容主要講解“Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)”吧!


假如確要修改,可以使用下面說的方式進(jìn)行通信:
首先,在子組件的UI點(diǎn)擊回調(diào)方法中,調(diào)用this.$emit('【自己設(shè)置事件名】')
向外發(fā)送一個(gè)事件;

接著各級(jí)父組件會(huì)收到這個(gè)事件,
則在父組件中 調(diào)用 子組件標(biāo)簽處,
@【事件名】= "回調(diào)方法名"的形式,監(jiān)聽該事件以及配置回調(diào)方法;
回調(diào)方法中就可 對 子組件用意修改 的 父組件數(shù)據(jù)字段 進(jìn)行修改;

注意,
觸發(fā)事件的命名,用駝峰命名法(如下heHeDa);
監(jiān)聽事件的命名,用橫桿間隔法(如下he-he-da)。

代碼:

<!DOCTYPE html><html><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Hello World! heheheheheheda</title>    <script src="https://unpkg.com/vue@next"></script></head><body>    <div id="heheApp"></div></body><script>    const app = Vue.createApp({        data() {            return {count: 1}        },        methods: {            handleItemEvent() {                this.count += 1;            }        },        template: `        <div>            <counter :count="count" @he-he-da="handleItemEvent"/>        </div>`    });    app.component('counter', {        props: ['count'],        methods: {            handleItemClick() {                this.$emit('heHeDa');            }        },        template:`        <div @click="handleItemClick">{{count}}</div>        `    });    const vm = app.mount('#heheApp');</script></html>

運(yùn)行,點(diǎn)擊組件:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

攜帶參數(shù)的事件 發(fā)送和監(jiān)聽回調(diào)

this.$emit()可以增加參數(shù)位,
父組件的監(jiān)聽回調(diào)中,
則可加形參位 用于接收參數(shù)(如handleItemEvent(param)中的 param);

代碼:

<script>    const app = Vue.createApp({        data() {            return {count: 1}        },        methods: {            handleItemEvent(param) {                this.count += param;            }        },        template: `        <div>            <counter :count="count" @add-count="handleItemEvent"/>        </div>`    });    app.component('counter', {        props: ['count'],        methods: {            handleItemClick() {                this.$emit('addCount', 8);            }        },        template:`        <div @click="handleItemClick">{{count}}</div>        `    });    const vm = app.mount('#heheApp');</script>

運(yùn)行,點(diǎn)擊效果:

Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)
子組件需 發(fā)送多個(gè)參數(shù) 亦可,只需在this.$emit()按需增加參數(shù)位,
父組件的監(jiān)聽回調(diào)中,增加對應(yīng)的形參 去接收就可:

<script>    const app = Vue.createApp({        data() {            return {count: 1}        },        methods: {            handleItemEvent(param1, param2, param3) {                this.count = this.count + param1 + param2 + param3;                console.log(this.count);            }        },        template: `        <div>            <counter :count="count" @add-count="handleItemEvent"/>        </div>`    });    app.component('counter', {        props: ['count'],        methods: {            handleItemClick() {                this.$emit('addCount', 8, 2, 6);            }        },        template:`        <div @click="handleItemClick">{{count}}</div>        `    });    const vm = app.mount('#heheApp');</script>

效果:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)



當(dāng)然 父組件 接收 子組件參數(shù) 后的 計(jì)算邏輯,
可以在 子組件傳參 的時(shí)候 計(jì)算完成 再傳給this.$emit()!
父組件接收時(shí),直接 受值就可(handleItemEvent(count));

<script>    const app = Vue.createApp({        data() {            return {count: 1}        },        methods: {            handleItemEvent(count) {                this.count = count;                console.log(this.count);            }        },        template: `        <div>            <counter :count="count" @add-count="handleItemEvent"/>        </div>`    });    app.component('counter', {        props: ['count'],        methods: {            handleItemClick() {                this.$emit('addCount', this.count + 16);            }        },        template:`        <div @click="handleItemClick">{{count}}</div>        `    });    const vm = app.mount('#heheApp');</script>

效果同上一個(gè)例子;

使用 組件的emits板塊 整理組件事件

實(shí)際開發(fā)場景中,我們一個(gè)組件自己設(shè)置的觸發(fā)事件可能會(huì)很多,
我們不可能一個(gè)一個(gè)去梳理核實(shí),
這個(gè)時(shí)候即可以使用 組件的emits板塊 來整理組件的事件;

可以把組件中 自己設(shè)置到的事件都寫在這里,方便梳理,提高可讀性
或者者把 想要定義的事件 寫在這里,
如此一來,假如不記得編寫對應(yīng)的自己設(shè)置事件,
Vue系統(tǒng)會(huì)在運(yùn)行時(shí) 給予警告

<script>    const app = Vue.createApp({        data() {            return {count: 1}        },        methods: {            handleItemEvent(count) {                this.count = count;                console.log(this.count);            }        },        template: `        <div>            <counter :count="count" @add-count="handleItemEvent"/>        </div>`    });    app.component('counter', {        props: ['count'],        emits: ['hehehe'],        methods: {            handleItemClick() {                this.$emit('addCount', this.count + 16);            }        },        template:`        <div @click="handleItemClick">{{count}}</div>        `    });    const vm = app.mount('#heheApp');</script>

假如不記得編寫對應(yīng)的自己設(shè)置事件,Vue系統(tǒng)會(huì)在運(yùn)行時(shí) 給予警告

Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

使用 組件emits板塊的 Object形式 校驗(yàn)外傳的參數(shù)值

可以根據(jù)需要,使用 組件emits板塊的 Object形式  校驗(yàn)外傳的參數(shù)值,
如下,子組件的emits板塊,
‘key’值定義對應(yīng)的事件名,‘value’值定義一個(gè)校驗(yàn)函數(shù),

返回true表示同意數(shù)值外傳,
返回false表示不同意,會(huì)給出警告;

<script>    const app = Vue.createApp({        data() {            return {count: 1}        },        methods: {            handleItemEvent(count) {                this.count = count;                console.log(this.count);            }        },        template: `        <div>            <counter :count="count" @add-count="handleItemEvent"/>        </div>`    });    app.component('counter', {        props: ['count'],        emits: {            addCount: (count) => {                if (count < 0) {                    return true;                }                return false;            }        },        methods: {            handleItemClick() {                this.$emit('addCount', this.count + 16);            }        },        template:`        <div @click="handleItemClick">{{count}}</div>        `    });    const vm = app.mount('#heheApp');</script>

運(yùn)行,點(diǎn)擊效果:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

結(jié)合$emit、v-bindv-model 實(shí)現(xiàn) 父子組件通信(數(shù)據(jù)雙向綁定)

v-model可以實(shí)現(xiàn)數(shù)據(jù)字段與DOM節(jié)點(diǎn)內(nèi)容的雙向綁定,
也可以實(shí)現(xiàn)數(shù)據(jù)字段與數(shù)據(jù)字段之間的雙向綁定;
v-bind只能是實(shí)現(xiàn)單向數(shù)據(jù)流

若不自己設(shè)置承接的字段名,則需要用modelValue作為默認(rèn)的承接字段名;
同時(shí),$emit()的一參默認(rèn)為update:modelValue,二參為綁定的數(shù)據(jù);

如下代碼,
子組件 的承接變量modelValue 同父組件的count字段 雙向綁定,
(實(shí)際上就是v-model的特性 —— 將 子組件的內(nèi)容即modelValue  同 父組件的數(shù)據(jù)字段雙向綁定)
而后顯示在子組件的DOM中({{modelValue}}):

<script>    const app = Vue.createApp({        data() {            return {count: 1}        },        template: `            <counter v-model="count"/>`    });    app.component('counter', {        props: ['modelValue'],        methods: {            handleItemClick() {                this.$emit('update:modelValue', this.modelValue + 16);                console.log(vm.$data.count);            }        },        template:`        <div @click="handleItemClick">{{modelValue}}</div>        `    });    const vm = app.mount('#heheApp');</script>

效果:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

當(dāng)然也可以自己設(shè)置字段名,
這種方式需要給v-model字段接一個(gè)字段名,
同時(shí)將這個(gè)字段名替代子組件中所有modelValue的位置:

<script>    const app = Vue.createApp({        data() {            return {count: 1}        },        template: `            <counter v-model:testField="count"/>`    });    app.component('counter', {        props: ['testField'],        methods: {            handleItemClick() {                this.$emit('update:testField', this.testField + 16);                console.log(vm.$data.count);            }        },        template:`        <div @click="handleItemClick">{{testField}}</div>        `    });    const vm = app.mount('#heheApp');</script>

實(shí)現(xiàn)效果與上例相同;

結(jié)合$emit、v-bindv-model 實(shí)現(xiàn) 父子組件通信(多個(gè)字段的應(yīng)用案例)

如下代碼,
父組件的count與子組件承接的testField字段,
父組件的count1與子組件承接的testField1字段,
分別實(shí)現(xiàn)了雙向綁定:

<script>    const app = Vue.createApp({        data() {            return {                count: 1,                count1: 1            }        },        template: `            <counter v-model:testField="count" v-model:testField1="count1"/>`    });    app.component('counter', {        props: ['testField','testField1'],        methods: {            handleItemClick() {                this.$emit('update:testField', this.testField + 16);                console.log("vm.$data.count", vm.$data.count);            },            handleItemClick1() {                this.$emit('update:testField1', this.testField1 + 8);                console.log("vm.$data.count1", vm.$data.count1);            }        },        template:`        <div @click="handleItemClick">{{testField}}</div>        <div @click="handleItemClick1">{{testField1}}</div>        `    });    const vm = app.mount('#heheApp');</script>

效果:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

自己設(shè)置修飾符

機(jī)制:在父組件調(diào)用處,在v-model后 使用自己設(shè)置修飾符
實(shí)現(xiàn)修飾符邏輯的地方,如點(diǎn)擊事件中,
通過this.modelModifiers.[自己設(shè)置修飾符名]返回的布爾值,
判斷客戶能否使用了修飾符,
進(jìn)而分別對使用與否做相應(yīng)的解決;
另外'modelModifiers'板塊中可以指定默認(rèn)值(下代碼指定為一個(gè)空對象{});

試驗(yàn)this.modelModifiers的作用

首先下面是一個(gè)空的解決,'modelModifiers'板塊中指定默認(rèn)值(下代碼指定為一個(gè)空對象{}),
mounted函數(shù)中打印 子組件modelModifiers屬性的內(nèi)容,

代碼如下,
運(yùn)行后,可以見打印了一個(gè)對象{captalize: true}
正是我們傳入的自己設(shè)置修飾符.captalize(這里未做解決)
【假如這里v-model不接修飾符,
console.log(this.modelModifiers);將打印一個(gè)空對象{}】:

<script>    const app = Vue.createApp({        data() {            return {                char: 'a'            }        },        template: `            <counter v-model.captalize="char"/>`    });    app.component('counter', {        props: {            'modelValue': String,            'modelModifiers': {                default: () => ({})            }        },        mounted() {            console.log(this.modelModifiers);        },        methods: {            handleClick() {                this.$emit('update:modelValue', this.modelValue + 'h');                console.log("vm.$data.count", vm.$data.char);            }        },        template:`        <div @click="handleClick">{{modelValue}}</div>        `    });    const vm = app.mount('#heheApp');</script>

Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

下面在子組件的點(diǎn)擊回調(diào)handleClick()中,通過this.modelModifiers.[自己設(shè)置修飾符名]實(shí)現(xiàn)自己設(shè)置修飾符邏輯

實(shí)現(xiàn)效果即 點(diǎn)擊之后使得對應(yīng)的字符串 全變大寫;

<script>    const app = Vue.createApp({        data() {            return {                testString: 'a'            }        },        template: `            <counter v-model.heheda="testString"/>`    });    app.component('counter', {        props: {            'modelValue': String,            'modelModifiers': {                default: () => ({})            }        },        mounted() {            console.log(this.modelModifiers);        },        methods: {            handleClick() {                let newValue = this.modelValue + 'h';                if(this.modelModifiers.heheda) {                    newValue = newValue.toUpperCase();                }                this.$emit('update:modelValue', newValue);                console.log("vm.$data.count", vm.$data.testString);            }        },        template:`        <div @click="handleClick">{{modelValue}}</div>        `    });    const vm = app.mount('#heheApp');</script>

效果:

Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

插槽【slot】【傳組件示例】

使用關(guān)鍵 主要分兩個(gè)部分:
自己設(shè)置子組件:
在需要 被父組件插入組件的位置,
使用<slot></slot>標(biāo)簽對臨時(shí)占位;

父組件:
在調(diào)用子組件標(biāo)簽對時(shí),
子組件標(biāo)簽對
寫上 要替換子組件標(biāo)簽對<slot></slot>位置的組件

【slot】的出現(xiàn),
方便父子組件之間數(shù)據(jù)的傳遞,
方便DOM的傳遞;

<!DOCTYPE html><html><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>Hello World! heheheheheheda</title>    <script src="https://unpkg.com/vue@next"></script></head><body>    <div id="heheApp"></div></body><script>    const app = Vue.createApp({        template: `            <myform>                <div>提交</div>            </myform>            <myform>                <button>提交</button>            </myform>`    });    app.component('myform', {        template:`        <div>            <input />            <slot></slot>            <br><br>        </div>        `    });    const vm = app.mount('#heheApp');</script></html>

運(yùn)行效果:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

注意,slot標(biāo)簽上是無法直接增加事件(修飾符)的,如有需要,可以在<slot>外層包裹一層<span>標(biāo)簽,再加上事件
<script>    const app = Vue.createApp({        template: `            <myform>                <div>提交</div>            </myform>            <myform>                <button>提交</button>            </myform>`    });    app.component('myform', {        methods: {            handleClick() {                console.log("heheda!!===");            }        },        template:`        <div>            <input />            <span @click="handleClick">                <slot></slot>            </span>                <br><br>        </div>        `    });    const vm = app.mount('#heheApp');</script>

運(yùn)行,點(diǎn)擊提交文本或者按鈕:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

插槽【傳 字符串示例】
<script>    const app = Vue.createApp({        template: `            <myform>                66666            </myform>            <myform>                88888            </myform>`    });    app.component('myform', {        methods: {            handleClick() {                console.log("heheda!!===");            }        },        template:`        <div>            <input />            <span @click="handleClick">                <slot></slot>            </span>                <br><br>        </div>        `    });    const vm = app.mount('#heheApp');</script>

Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

插槽【傳 自己設(shè)置子組件 示例】
<script>    const app = Vue.createApp({        template: `            <myform>                <test />            </myform>            <myform>                88888            </myform>`    });    app.component('test', {        template: `<div>test component</div>`    })    app.component('myform', {        methods: {            handleClick() {                console.log("heheda!!===");            }        },        template:`        <div>            <input />            <span @click="handleClick">                <slot></slot>            </span>                <br><br>        </div>        `    });    const vm = app.mount('#heheApp');</script>

運(yùn)行:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

插槽作用域問題

盡管,父組件中 往子組件標(biāo)簽間 插入的組件 會(huì)替換子組件的插槽位,
但是父組件中 往子組件標(biāo)簽間 插入的組件,
其所使用的數(shù)據(jù)字段,依然是父組件的,而非子組件

父組件的template中 調(diào)用的數(shù)據(jù)是 父組件中的 data;
子組件的template中 調(diào)用的數(shù)據(jù)是 子組件中的 data;

<script>    const app = Vue.createApp({        data() {            return {                text: '提交'            }        },        template: `            <myform>                <div>{{text}}</div>            </myform>            <myform>                <button>{{text}}</button>            </myform>`    });    app.component('myform', {        methods: {            handleClick() {                console.log("heheda!!===");            }        },        template:`        <div>            <input />            <span @click="handleClick">                <slot></slot>            </span>                <br><br>        </div>        `    });    const vm = app.mount('#heheApp');</script>

Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

插槽 UI默認(rèn)值

可以在子組件的插槽<slot>標(biāo)簽間 編寫默認(rèn)值,
假如父組件沒有使用 組件 注入插槽
則對應(yīng)位置 會(huì)顯示默認(rèn)值

<script>    const app = Vue.createApp({        data() {            return {                text: '提交'            }        },        template: `            <myform>                <div>{{text}}</div>            </myform>            <myform>                <button>{{text}}</button>            </myform>            <myform>            </myform>`    });    app.component('myform', {        methods: {            handleClick() {                console.log("heheda!!===");            }        },        template:`        <div>            <input />            <span @click="handleClick">                <slot>default value</slot>            </span>                <br><br>        </div>        `    });    const vm = app.mount('#heheApp');</script>

效果:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

插槽的靈活拆分與應(yīng)用【具名插槽】
  • 使得插槽的 父組件注入部分 和 子組件占位部分,能夠更加靈活的布局,

    可以通過v-slot:[插槽名]來對一組插槽命名,
    父組件定義之后 插槽名及其對應(yīng)的組件之后,

    子組件只要要在要占位的地方,
    配合name屬性 使用對應(yīng)命名的<slot>標(biāo)簽,
    就可將對應(yīng)的父組件插槽組件占用過來;

  • 父組件 的插槽注入部分的組件,
    需要用<template>標(biāo)簽組包裹起來,
    使用v-slot:[插槽名]命名一組插槽;

  • 子組件使用<slot name="[插槽名]"></slot>的形式,進(jìn)行插槽組件塊的臨時(shí)占用;

<script>    const app = Vue.createApp({        template: `            <layout>                <template v-slot:header>                    <div>頭部</div>                </template>                <template v-slot:footer>                    <div>尾部</div>                </template>            </layout>`    });    app.component('layout', {        template:`        <div>            <slot name="header"></slot>            <div>content</div>            <slot name="footer"></slot>        </div>        `    });    const vm = app.mount('#heheApp');</script>

效果:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

v-slot指令的簡寫

v-slot:[插槽名] 可以簡寫成 #[插槽名]

<script>    const app = Vue.createApp({        template: `            <layout>                <template #header>                    <div>頭部</div>                </template>                <template #footer>                    <div>尾部</div>                </template>            </layout>`    });    app.component('layout', {        template:`        <div>            <slot name="header"></slot>            <div>content</div>            <slot name="footer"></slot>        </div>        `    });    const vm = app.mount('#heheApp');</script>

實(shí)現(xiàn)的效果同上例;

普通的v-for例子 進(jìn)行 列表渲染

下面在子組件中,
使用v-for指令 循環(huán) 子組件的數(shù)據(jù),創(chuàng)立DOM組件:

<script>    const app = Vue.createApp({        template: `            <test-list />`    });    app.component('test-list', {        data(){            return {                 list: ["heheda", "xixi" , "lueluelue"]            }        },        template:`        <div>            <div v-for="item in list">{{item}}</div>        </div>        `    });    const vm = app.mount('#heheApp');</script>

運(yùn)行效果:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

v-for結(jié)合v-bindv-slot、<slot>做列表渲染

作用:給數(shù)據(jù)子組件提供,
列表UI實(shí)現(xiàn)父組件調(diào)用處提供,
相似于回調(diào)接口的設(shè)計(jì)邏輯?。?!

子組件使用v-for循環(huán)獲取數(shù)據(jù),
每一輪迭代 取得的子項(xiàng)數(shù)據(jù),
通過v-bind設(shè)置到占位的<slot>標(biāo)簽中,

父組件中,在引用的 子組件標(biāo)簽上,
使用v-slot承接 子組件通過v-bind傳來的所有數(shù)據(jù)字段,
同時(shí)將這些字段打包成一個(gè)相似JSONObject結(jié)構(gòu) 字段,
并為這個(gè)字段 指定一個(gè)形參名(如下代碼中的mySlotProps);

【注意!
前面是,
使用v-slot命名父組件中 擬填充插槽的組件,
子組件在<slot>標(biāo)簽上,通過name=使用 父組件的命名,靈活填充插槽;
而這里是,
slot反而是起到了相似props的作用,而非之前的命名組件作用!】

擬填充插槽的DOM組件中,
使用方才 v-slot指定的形參,用于開箱取數(shù)據(jù)

<script>    const app = Vue.createApp({        template: `            <test-list v-slot="mySlotProps">                 <div>{{mySlotProps.item}}</div>            </test-list>`    });    app.component('test-list', {        data(){            return {                 list: ["heheda", "xixi" , "lueluelue"]            }        },        template:`        <div>            <slot v-for="item in list" :item="item" />        </div>        `    });    const vm = app.mount('#heheApp');</script>

運(yùn)行效果同上例;

使用解構(gòu)概念進(jìn)行簡寫

使用v-slot="{item}"替代前面的props的結(jié)構(gòu)邏輯形式;
意義是,把mySlotProps這個(gè)承接屬性的字段,
里面的item屬性直接解構(gòu) 剝?nèi)?/code>出來,直接拿來用;

<script>    const app = Vue.createApp({        template: `            <test-list v-slot="{item}">                 <div>{{item}}</div>            </test-list>`    });    app.component('test-list', {        data(){            return {                 list: ["heheda", "xixi" , "lueluelue"]            }        },        template:`        <div>            <slot v-for="item in list" :item="item" />        </div>        `    });    const vm = app.mount('#heheApp');</script>

運(yùn)行效果同上例;

動(dòng)態(tài)組件
常規(guī)的利用雙向綁定特性,通過點(diǎn)擊事件切換UI的寫法:
<script>    const app = Vue.createApp({        data() {            return {                currentItem: 'input-item'            }        },        methods: {            handlerClick() {                this.currentItem === 'input-item'?                this.currentItem = 'div-item': this.currentItem = 'input-item'            }        },        template: `            <input-item v-show="currentItem === 'input-item'" />            <div-item v-show="currentItem === 'div-item'" />            <button @click="handlerClick">切換DOM組件</button>`    });    app.component('input-item', {        template:`        <input />`    });    app.component('div-item', {        template:`<div>heheda</div>`    });    const vm = app.mount('#heheApp');</script>

運(yùn)行效果:

Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

動(dòng)態(tài)組件寫法
  • 語法:
    一般在父組件中,
    使用占位標(biāo)簽<component :is="[需顯示的 子組件名]" />
    效果即 占位位置,會(huì)顯示 is屬性 指定組件名的子組件;
    另外,
    使用<keep-alive>標(biāo)簽,包裹<component :is="[需顯示的 子組件名]" />
    可以是切換組件的時(shí)候,能夠緩存組件的數(shù)據(jù),
    如一個(gè)有輸入數(shù)據(jù)的<input> 切換成一個(gè)其余組件 再切換 回來的時(shí)候,
    可以保留一開始的輸入數(shù)據(jù)

<script>    const app = Vue.createApp({        data() {            return {                currentItem: 'input-item'            }        },        methods: {            handlerClick() {                console.log("handlerClick ----- ");                this.currentItem === 'input-item'?                this.currentItem = 'div-item': this.currentItem = 'input-item'            }        },        template: `            <keep-alive>                <component :is="currentItem" />            </keep-alive>            <button @click="handlerClick">切換DOM組件</button>`    });    app.component('input-item', {        template:`        <input />`    });    app.component('div-item', {        template:`<div>heheda</div>`    });    const vm = app.mount('#heheApp');</script>

運(yùn)行效果:
初始為有輸入數(shù)據(jù)的輸入框:

Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)點(diǎn)擊切換為文本組件:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)再次點(diǎn)擊,切換為有輸入數(shù)據(jù)的輸入框,
因?yàn)?code><keep-alive>
的作用,數(shù)據(jù)緩存下來,沒有丟失,
假如沒加<keep-alive>,這里會(huì)是空的輸入框:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

異步組件

首先,
本文在此案例之前的所有案例,都是同步組件
即隨即渲染,一個(gè)線程運(yùn)行;

下面是異步(自己設(shè)置子)組件,
可以設(shè)定在某個(gè)時(shí)刻開始,推遲一個(gè)時(shí)延后,再執(zhí)行渲染:

<script>    const app = Vue.createApp({        template: `            <div>                <div-item />                <my-async-item />            </div>`            });    app.component('div-item', {        template:`<div>heheda heheda</div>`    });    app.component('my-async-item', Vue.defineAsyncComponent(() => {        return new Promise((resolve, reject) => {            setTimeout(() => {                resolve({                    template: `<div>this is my async component</div>`                })            }, 4000)        })    }))    const vm = app.mount('#heheApp');</script>

關(guān)鍵代碼【異步(自己設(shè)置子)組件】:

    app.component('my-async-item', Vue.defineAsyncComponent(() => {        return new Promise((resolve, reject) => {            setTimeout(() => {                resolve({                    template: `<div>this is my async component</div>`                })            }, 4000)        })    }))

運(yùn)行效果:Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)

到此,相信大家對“Vue3父子組件間通信和組件間雙向綁定怎么實(shí)現(xiàn)”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI