iT邦幫忙

2025 iThome 鐵人賽

DAY 19
0
Vue.js

Vue.js 新手入門之路系列 第 19

Vue.js 新手入門之路 - props (二)

  • 分享至 

  • xImage
  •  

今天持續來學習有關 props 的相關知識

單向資料流

  • 父元件的狀態改變,會自動傳到子元件的 props
  • 子元件無法直接修改 props,否則 Vue 會警告
    因為這樣的資料流清晰、可追蹤,避免「子元件偷偷改變父元件的狀態」造成混亂

在子元件裡把 prop 當作初始值,存到自己的 data 裡

<script setup>
import { ref } from 'vue'

const props = defineProps({
  initialCounter: Number
})

const attr = 'box'

const counter = ref(props.initialCounter)

function increment() {
  counter.value++
}
</script>

<template>
  <div :class="attr">
    <button @click="increment">Count: {{ counter }} </button>
  </div>
</template>

<style scoped>
.box{
  display: flex;
  text-align: center;
  justify-content: center;
  font-size: x-large;
  border: solid;
  margin-left: 450px;
  margin-top: 5px;
  height: 200px;
  width: 350px;
  padding: 35px;
}
</style>
<script setup>
import { computed } from 'vue'

const props = defineProps({
  size: String
})

const normalizedSize = computed(() =>
  props.size.trim().toLowerCase()
)

const attr = 'box'
</script>

<template>
  <div :class="attr">
    origin: {{ props.size }}  
    normalize: {{ normalizedSize }}
  </div>
</template>

<style scoped>
.box{
  display: flex;
  text-align: center;
  justify-content: center;
  flex-direction: column;
  font-size: x-large;
  border: solid;
  margin-left: 450px;
  margin-top: 5px;
  height: 200px;
  width: 350px;
  padding: 35px;
}
</style>

若真的需要更改 props ,則應使用計算數性做轉換,維持單向資料流的乾淨
https://ithelp.ithome.com.tw/upload/images/20250908/20178296ydWIAEqy2F.png


上一篇
Vue.js 新手入門之路 - props
下一篇
Vue.js 新手入門之路 - emit 事件
系列文
Vue.js 新手入門之路25
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言