Vue 'expose' 選項
示例
使用 expose
選項使一個方法可供父元件使用。
export default {
expose: ['createMessage'],
data() {
return {
message: ' '
}
},
methods: {
createMessage(msg) {
this.message += msg + ' '
}
}
}
執行示例 »
檢視下面的更多示例
定義和用法
expose
選項用於列出哪些屬性可以透過模板引用(template refs)提供給父元件。
預設情況下,所有子元件的屬性都可以透過使用模板引用供父元件訪問。
這意味著,如果子元件沒有 expose
選項,並且父元件在子元件上使用了內建屬性 ref="childComp"
,那麼父元件可以使用程式碼 this.$refs.childComp.message
來訪問子元件中的資料屬性 'message'。(請參見示例 1)
但是,在使用 expose
選項時,只有 expose
選項中列出的屬性才能被父元件訪問。(請參見示例 2)
更多示例
示例 1
在子元件中未使用 expose
選項,因此子元件中的所有屬性都可以供父元件訪問。
ChildComp.vue
:
<template>
<div>
<h3>ChildComp.vue</h3>
<p>Message from parent component:</p>
<p id="pEl">{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: ' '
}
},
methods: {
createAlert() {
alert('This is an alert, from the child component')
}
}
}
</script>
<style scoped>
div {
border: solid black 1px;
padding: 10px;
max-width: 350px;
margin-top: 20px;
}
#pEl {
background-color: lightgreen;
font-family: 'Courier New', Courier, monospace;
}
</style>
App.vue
:
<template>
<h2>Example expose Option</h2>
<p>The 'expose' option is not used, so all child properties are available to the parent by default, both the 'message' data property, and the 'createAlert()' method:</p>
<button v-on:click="{ this.$refs.childComp.message += 'Hello! '; }">Write 'Hello!'</button>
<button v-on:click="{ this.$refs.childComp.createAlert(); }">Create alert</button>
<child-comp ref="childComp"/>
</template>
執行示例 »
示例 2
從父元件呼叫子元件的 'createMessage' 方法不起作用,因為子元件的 expose
選項只列出了 'message' 資料屬性。
ChildComp.vue
:
<template>
<div>
<h3>ChildComp.vue</h3>
<p>Message from parent component:</p>
<p id="pEl">{{ message }}</p>
</div>
</template>
<script>
export default {
expose: ['message'],
data() {
return {
message: ' '
}
},
methods: {
createMessage(msg) {
this.message += msg + ' '
}
}
}
</script>
<style scoped>
div {
border: solid black 1px;
padding: 10px;
max-width: 350px;
margin-top: 20px;
}
#pEl {
background-color: lightgreen;
font-family: 'Courier New', Courier, monospace;
}
</style>
App.vue
(高亮顯示的行不起作用)
<template>
<h2>Example expose Option</h2>
<p>Only the 'message' data property is listed in the 'expose' option, so the 'createMessage' method from the child component is not available, and will not work:</p>
<input type="text" v-model="inpText" placeholder="Write something">
<button v-on:click="useMet">Use exposed method</button>
<child-comp ref="childComp"/>
</template>
<script>
export default {
data() {
return {
inpText: ''
}
},
methods: {
useMet() {
this.$refs.childComp.createMessage(this.inpText);
}
},
mounted() {
this.$refs.childComp.message = 'Initial message!';
}
}
</script>
執行示例 »
相關頁面
Vue 教程:Vue Template Refs
Vue 教程:Vue Components
Vue 參考:Vue 'ref' 屬性
Vue 參考:Vue $refs 物件