Vue 'expose' 选项
实例
使用 expose 选项使方法可供父组件使用。
export default {expose: ['createMessage'],data() {return {message: ' '}},methods: {createMessage(msg) {this.message += msg + ' '}}}
定义与用法
expose 选项用于列出通过模板引用可用于父组件的特性。
默认情况下,通过使用模板引用,父组件可以使用所有子组件属性。
这意味着,如果子组件没有 expose 选项,并且父组件在子组件上使用内置属性 ref="childComp",则父组件可以使用以下代码访问子组件中的数据属性 "message",代码为 this.$refs.childComp.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>
关联页面
Vue 教程: Vue 模板引用
Vue 教程: Vue 组件
Vue 参考引用: Vue 'ref' 属性
Vue 参考引用: Vue $refs 对象