Vue 'expose' 选项

实例

使用 expose 选项使方法可供父组件使用。

  1. export default {
  2. expose: ['createMessage'],
  3. data() {
  4. return {
  5. message: ' '
  6. }
  7. },
  8. methods: {
  9. createMessage(msg) {
  10. this.message += msg + ' '
  11. }
  12. }
  13. }

定义与用法

expose 选项用于列出通过模板引用可用于父组件的特性。

默认情况下,通过使用模板引用,父组件可以使用所有子组件属性。

这意味着,如果子组件没有 expose 选项,并且父组件在子组件上使用内置属性 ref="childComp",则父组件可以使用以下代码访问子组件中的数据属性 "message",代码为 this.$refs.childComp.message (参见实例 1)

但是,当使用 expose 选项时,只有 expose 选项中列出的属性对父级可用。(参见实例 2)


更多实例

实例 1

expose 选项未在子组件中使用,因此子组件中的所有特性都可用于父组件。

ChildComp.vue:

  1. <template>
  2. <div>
  3. <h3>ChildComp.vue</h3>
  4. <p>Message from parent component:</p>
  5. <p id="pEl">{{ message }}</p>
  6. </div>
  7. </template>
  8. <script>
  9. export default {
  10. data() {
  11. return {
  12. message: ' '
  13. }
  14. },
  15. methods: {
  16. createAlert() {
  17. alert('This is an alert, from the child component')
  18. }
  19. }
  20. }
  21. </script>
  22. <style scoped>
  23. div {
  24. border: solid black 1px;
  25. padding: 10px;
  26. max-width: 350px;
  27. margin-top: 20px;
  28. }
  29. #pEl {
  30. background-color: lightgreen;
  31. font-family: 'Courier New', Courier, monospace;
  32. }
  33. </style>

App.vue:

  1. <template>
  2. <h2>Example expose Option</h2>
  3. <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>
  4. <button v-on:click="{ this.$refs.childComp.message += 'Hello! '; }">Write 'Hello!'</button>
  5. <button v-on:click="{ this.$refs.childComp.createAlert(); }">Create alert</button>
  6. <child-comp ref="childComp"/>
  7. </template>

关联页面

Vue 教程: Vue 模板引用

Vue 教程: Vue 组件

Vue 参考引用: Vue 'ref' 属性

Vue 参考引用: Vue $refs 对象

分类导航