Vue expose 选项


示例

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

export default {
  expose: ['createMessage'],
  data() {
    return {
      message: ' '
    }
  },
  methods: {
    createMessage(msg) {
      this.message += msg + ' '
    }
  }
}
运行示例 »

请参阅下面的更多示例


定义和用法

这个exposeoption 用于通过模板引用列出父组件可用的属性。

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

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

但是,当使用expose选项,仅列出的属性expose选项可供家长使用。 (参见示例2)


更多示例

示例1

这个expose子组件中没有使用 option,因此子组件中的所有属性都可供父组件使用。

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”方法不起作用,因为只列出了“message”数据属性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 {
  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 模板参考

Vue教程:Vue 组件

Vue参考:Vue 'ref' 属性

Vue参考:Vue $refs 对象