1. 程式人生 > >vue的元件之間傳值方法

vue的元件之間傳值方法

父元件

<template>
  <div>
    這是父元件
    <children v-bind:parentToChild="toChild" v-on:showChildMsg="formChild"></children>
    <!-- 使用vind:引數名 繫結傳值,使用on:引數名 來監聽接收子元件傳來的資訊-->
    {{showChildMsg}}
  </div>
</template>

<script>
import children from "./children.vue
"; export default { name: "HelloWorld", data() { return { toChild:"父元件傳值給子元件", showChildMsg:'' }; }, methods: { formChild:function(data){ //監聽子元件子元件傳值 this.showChildMsg = data; } }, components: { children } }; </script> <style scoped
> </style>

子元件

<style scoped>
/* css */
</style>
<template>
  <div class id>
    {{parentToChild}}
    <br/>
    <button @click="goParent">點擊向父元件傳值</button>
  </div>
</template>
<script>
export default {
  data() {
    return {};
  },
  methods: {
    goParent: 
function() { this.$emit("showChildMsg", "這是子元件傳值給父元件"); //子元件 通過$emit函式向父元件傳值,這個showChildMsg引數名對應的就是父元件裡面的v-on:showChildMsg引數名 } }, activated() {}, props: ["parentToChild"] }; </script>