1. 程式人生 > 其它 >vue 父元素給子元素傳資料 props

vue 父元素給子元素傳資料 props

技術標籤:vuevue

在這裡插入圖片描述
在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
  <!--
    點選父元件控制子元件 div 的顯示隱藏
  -->
  <div id="app">
    <Fa />
  </div>
  <!-- 父元件 -->
  <template id="fa">
    <div class="fa">
      我是父元素
      <button @click="toggle">toggle</button>
      <hr>
      <Son :hehe="toggleSon" age="16"></Son>
    </div>
  </template>
  <!-- 子元件 -->
  <template id="son">
    <div v-if="hehe">
      {{hehe}} {{age}}
    </div>
  </template>
  <script>
    Vue.component('Fa', {
      template: "#fa",
      data() {
        return {
          toggleSon: true
        }
      },
      methods: {
        toggle () {
          this.toggleSon = !this.toggleSon
        }
      }
    })
    Vue.component('Son', {
      template: "#son",
      props: ['hehe', 'age'], // 該元件可以通過 hehe 傳遞引數
    })
    new Vue({
      el: '#app',
      data: {
      }
    })
  </script>
</body>
</html>