引入組件
-
全局引入
在main.js文件中引入并注冊
import ChildrenDemo from '@/views/components/ChildrenDemo' Vue.component('ChildrenDemo',ChildrenDemo)// 第一個參數(shù) 全局組件的名字(字符串類型),第二個參數(shù):引入的組件名(一般都與組件名保持一致)
之后就可以全局使用組件了
-
局部引入
在父組件中引入
import ChildrenDemo from '@/views/components/ChildrenDemo' export default { components: { ChildrenDemo }, }
之后就可以在父組件中使用組件了
<ChildrenDemo></ChildrenDemo> <!-- 或 --> <children-demo></children-demo>
一、props屬性綁定(父組件向子組件傳遞數(shù)據(jù))
在子組件 prop 中可以注冊一些自定義組件屬性,父組件調(diào)用子組件時可以向 prop 中的自定義屬性傳值。
子組件代碼:
<template>
<div class="ChildrenDemo">
<h1>{{title}}</h1>
</div>
</template>
<script>
export default {
name: 'ChildrenDemo',
props:['title'],
components: {
},
data () {
return {
}
}
}
</script>
父組件代碼
<template>
<div class="parent">
<ChildrenDemo title="向子組件傳遞的title值"></ChildrenDemo>
</div>
</template>
prop 也可以通過 v-bind
動態(tài)賦值
<ChildrenDemo :title="xxx"></ChildrenDemo>
如果要將一個對象的所有 property 都作為 prop 傳入,你可以使用不帶參數(shù)的 v-bind
例如,對于一個給定的對象 post
post: {
id: 1,
title: 'My Journey with Vue'
}
傳給子組件
<blog-post v-bind="post"></blog-post>
等價于:
<blog-post
v-bind:id="post.id"
v-bind:title="post.title"
></blog-post>
props的更多寫法
-
字符串?dāng)?shù)組形式
props: ['title', 'likes', 'isPublished', 'commentIds', 'author']
-
指定prop值類型
props: { title: String, likes: Number, isPublished: Boolean, commentIds: Array, author: Object, callback: Function, contactsPromise: Promise // or any other constructor }
-
指定 prop 的驗證要求
當(dāng) prop 驗證失敗的時候,(開發(fā)環(huán)境構(gòu)建版本的) Vue 將會產(chǎn)生一個控制臺的警告。
props: { // 基礎(chǔ)的類型檢查 (`null` 和 `undefined` 會通過任何類型驗證) propA: Number, // 多個可能的類型 propB: [String, Number], // 必填的字符串 propC: { type: String, required: true }, // 帶有默認(rèn)值的數(shù)字 propD: { type: Number, default: 100 }, // 帶有默認(rèn)值的對象 propE: { type: Object, // 對象或數(shù)組默認(rèn)值必須從一個工廠函數(shù)獲取 default: function () { return { message: 'hello' } } }, // 自定義驗證函數(shù) propF: { validator: function (value) { // 這個值必須匹配下列字符串中的一個 return ['success', 'warning', 'danger'].indexOf(value) !== -1 } } },
注意: prop 會在一個組件實例創(chuàng)建之前進(jìn)行驗證,所以實例的 property (如
data
、computed
等) 在default
或validator
函數(shù)中是不可用的。
prop雙向綁定
一般情況下,子組件不能直接修改從父組件接收的屬性值,否則會報錯,如果子組件需要接收值后處理再使用,可以將接收的值賦值給子組件本身的屬性,如data中的屬性或計算屬性。
如果希望子組件prop父組件中的值改變時,將變化同步到父組件中,可使用事件監(jiān)聽或**.sync修飾符**
.sync修飾符
.sync修飾符是一個語法糖,本質(zhì)上等同于事件監(jiān)聽的方法
參考:vue的.sync修飾符用法及原理詳解_weixin_58206976的博客-CSDN博客_vuesync修飾符
父組件
<h1>父組件title值:{{ title }}</h1>
<ChildrenDemo :title.sync="title"></ChildrenDemo>
子組件
<template>
<div class="ChildrenDemo">
<h1>子組件</h1>
<input type="text" v-model="childTitle" />
</div>
</template>
<script>
export default {
props: ["title"],
data() {
return {};
},
computed: {
childTitle: {
get() {
return this.title;
},
set(val) {
this.$emit("update:title", val);//更新父組件中的title
},
},
}
};
</script>
效果:當(dāng)子組件中input內(nèi)容改變時,父組件中的title會同步改變
二、監(jiān)聽子組件事件(子組件向父組件傳遞數(shù)據(jù),子組件觸發(fā)父組件方法)
通過 vue 實例方法 vm.$emit
子組件可以自定義一個事件提交給父組件,觸發(fā)父組件的方法,父組件通過監(jiān)聽子組件的自定義事件可以接收子組件傳遞的數(shù)據(jù)。
子組件
<template>
<div class="ChildrenDemo">
<h1>子組件</h1>
<button @click="changeParentTitle">點擊更改父組件title</button>
</div>
</template>
<script>
export default {
components: {},
data() {
return {};
},
methods: {
changeParentTitle() {
this.$emit("childEvent", "子組件傳給父組件的title")//第一個參數(shù)是提交的事件名,后面的參數(shù)可以是多個需要傳遞給父組件的參數(shù)
}
}
};
</script>
父組件
<template>
<div class="home">
<h1>父組件title值:{{ title }}</h1>
<ChildrenDemo :title="title" @childEvent="changeTitle"></ChildrenDemo>
</div>
</template>
<script>
import ChildrenDemo from "@/views/components/ChildrenDemo";
export default {
components: {
ChildrenDemo,
},
data() {
return {
title: "My Journey with Vue"
};
},
methods: {
changeTitle: function (str) {
this.title = str
},
},
};
</script>
上例中的操作和傳遞的值都比較簡單,也可以在事件處理函數(shù)中直接使用表達(dá)式,父組件通過 $event
訪問被子組件拋出的值
子組件:文章來源地址http://www.zghlxwxcb.cn/news/detail-415302.html
<button @click="$emit('childEvent', '子組件傳給父組件的title')">點擊更改父組件title</button>
父組件:
<ChildrenDemo :title="title" @childEvent="title = $event"></ChildrenDemo>
三、使用 $refs (父組件訪問子組件的數(shù)據(jù)和方法)
父組件使用 $refs 可以訪問子組件的數(shù)據(jù)和方法
使用時需在調(diào)用子組件時給子組件定義一個 ref 名
<ChildrenDemo ref="childrenDemo"></ChildrenDemo>
<button @click="getChildData">點擊獲取子組件數(shù)據(jù)</button>
getChildData: function () {
let child = this.$refs.childrenDemo//獲取子組件實例
console.log(child.value);//訪問子組件屬性
child.childFn() //調(diào)用子組件的childFn()方法
},
注意:
$refs
只會在組件渲染完成之后生效,并且它們不是響應(yīng)式的。這僅作為一個用于直接操作子組件的“逃生艙”——你應(yīng)該避免在模板或計算屬性中訪問$refs
。- 由于ref 需要在dom渲染完成后才會有,在使用的時候確保dom已經(jīng)渲染完成。比如在生命周期
mounted(){}
鉤子中調(diào)用,或者在this.$nextTick(()=>{})
中調(diào)用。
四、使用$parent(子組件訪問父組件的數(shù)據(jù)和方法)
$parent
property 可以用來從一個子組件訪問父組件的實例文章來源:http://www.zghlxwxcb.cn/news/detail-415302.html
子組件:
<button @click="getParentData">點擊獲取父組件數(shù)據(jù)</button>
getParentData(){
let parent = this.$parent //獲取父組件實例
console.log(parent.parentValue) //訪問父組件屬性
parent.parentFn() //調(diào)用父組件的方法parentFn()
}
到了這里,關(guān)于Vue組件通信——父子組件通信的四種方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!